2014-10-08 3 views
3

Поэтому у меня есть этот контроллер с именем guests_controller.rb который выглядит следующим образом:TypeError: неправильный аргумент типа класс (ожидаемый модуль) с беспокойством контроллера

class GuestsController < ApplicationController 
    include Data 

    def index 
     display_data("db") 
     display_data("session") 
    end 

    def new 
     @guest = Guest.new 
    end 

    def create 
     case params[:option] 
      when '0' 
       logger.debug 'Salvestame andmebaasi' 
       save_data("db") 
      when '1' 
       logger.debug 'Salvestame sessiooni' 
       save_data("session") 
     end 
    end 

    private 
    def guest_params 
     params.require(:guest).permit(:name, :text) 
    end 
end 

А также у меня есть опасение, по имени data.rb в контроллерах/concens /:

module Data 
    extend ActiveSupport:Concern 

    def save_data(save_method) 
     case save_method 
      when "db" 
       @guest = Guest.new(guest_params) 
       if @guest.save 
        flash[:success] = "New guest entry created!" 
        redirect_to guests_path 
       else 
        render 'new' 
       end 
      when "session" 
       name = params[:guest][:name].to_s 
       text = params[:guest][:text].to_s 

       @guests_session = session[:guests] 

       if session[:guests].nil? 
        @guests_session = [{:name => 'temp', :text => 'temp'}] 
       else 
        logger.debug @guests_session 
        @guests_session.push({:name => name, :text => text}) 
       end 

       session[:guests] = @guests_session 
       redirect_to guests_path 
     end 
    end 

    def display_data(display_method) 
     case display_method 
      when "db" 
       @guests = Guest.all 
      when "session" 
       if session[:guests].nil? 
        @guests_session = [{:name => 'temp', :text => 'temp'}] 
       else 
        #@guests_session = [{:name => 'temp', :text => 'temp'}] 
        @guests_session = session[:guests] 
       end 
     end 
    end 
end 

Теперь, когда я открываю соответствующий вид я получаю эту ошибку:

TypeError в GuestsController # индекс неверный аргумент типа класса (ожидается модуль)

С StackTrace:

app/controllers/guests_controller.rb:2:in `include' 
app/controllers/guests_controller.rb:2:in `<class:GuestsController>' 
app/controllers/guests_controller.rb:1:in `<top (required)>' 
activesupport (4.1.5) lib/active_support/dependencies.rb:443:in `load' 
activesupport (4.1.5) lib/active_support/dependencies.rb:443:in `block in load_file' 
activesupport (4.1.5) lib/active_support/dependencies.rb:633:in `new_constants_in' 
activesupport (4.1.5) lib/active_support/dependencies.rb:442:in `load_file' 
activesupport (4.1.5) lib/active_support/dependencies.rb:342:in `require_or_load' 
activesupport (4.1.5) lib/active_support/dependencies.rb:480:in `load_missing_constant' 
activesupport (4.1.5) lib/active_support/dependencies.rb:180:in `const_missing' 
activesupport (4.1.5) lib/active_support/inflector/methods.rb:238:in `const_get' 
activesupport (4.1.5) lib/active_support/inflector/methods.rb:238:in `block in constantize' 
activesupport (4.1.5) lib/active_support/inflector/methods.rb:236:in `each' 
activesupport (4.1.5) lib/active_support/inflector/methods.rb:236:in `inject' 
activesupport (4.1.5) lib/active_support/inflector/methods.rb:236:in `constantize' 
activesupport (4.1.5) lib/active_support/dependencies.rb:552:in `get' 
activesupport (4.1.5) lib/active_support/dependencies.rb:583:in `constantize' 
actionpack (4.1.5) lib/action_dispatch/routing/route_set.rb:78:in `controller_reference' 
actionpack (4.1.5) lib/action_dispatch/routing/route_set.rb:68:in `controller' 
actionpack (4.1.5) lib/action_dispatch/routing/route_set.rb:46:in `call' 
actionpack (4.1.5) lib/action_dispatch/journey/router.rb:71:in `block in call' 
actionpack (4.1.5) lib/action_dispatch/journey/router.rb:59:in `each' 
actionpack (4.1.5) lib/action_dispatch/journey/router.rb:59:in `call' 
actionpack (4.1.5) lib/action_dispatch/routing/route_set.rb:678:in `call' 
warden (1.2.3) lib/warden/manager.rb:35:in `block in call' 
warden (1.2.3) lib/warden/manager.rb:34:in `catch' 
warden (1.2.3) lib/warden/manager.rb:34:in `call' 
rack (1.5.2) lib/rack/etag.rb:23:in `call' 
rack (1.5.2) lib/rack/conditionalget.rb:25:in `call' 
rack (1.5.2) lib/rack/head.rb:11:in `call' 
actionpack (4.1.5) lib/action_dispatch/middleware/params_parser.rb:27:in `call' 
actionpack (4.1.5) lib/action_dispatch/middleware/flash.rb:254:in `call' 
rack (1.5.2) lib/rack/session/abstract/id.rb:225:in `context' 
rack (1.5.2) lib/rack/session/abstract/id.rb:220:in `call' 
actionpack (4.1.5) lib/action_dispatch/middleware/cookies.rb:560:in `call' 
activerecord (4.1.5) lib/active_record/query_cache.rb:36:in `call' 
activerecord (4.1.5) lib/active_record/connection_adapters/abstract/connection_pool.rb:621:in `call' 
activerecord (4.1.5) lib/active_record/migration.rb:380:in `call' 
actionpack (4.1.5) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call' 
activesupport (4.1.5) lib/active_support/callbacks.rb:82:in `run_callbacks' 
actionpack (4.1.5) lib/action_dispatch/middleware/callbacks.rb:27:in `call' 
actionpack (4.1.5) lib/action_dispatch/middleware/reloader.rb:73:in `call' 
actionpack (4.1.5) lib/action_dispatch/middleware/remote_ip.rb:76:in `call' 
actionpack (4.1.5) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call' 
actionpack (4.1.5) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call' 
railties (4.1.5) lib/rails/rack/logger.rb:38:in `call_app' 
railties (4.1.5) lib/rails/rack/logger.rb:20:in `block in call' 
activesupport (4.1.5) lib/active_support/tagged_logging.rb:68:in `block in tagged' 
activesupport (4.1.5) lib/active_support/tagged_logging.rb:26:in `tagged' 
activesupport (4.1.5) lib/active_support/tagged_logging.rb:68:in `tagged' 
railties (4.1.5) lib/rails/rack/logger.rb:20:in `call' 
actionpack (4.1.5) lib/action_dispatch/middleware/request_id.rb:21:in `call' 
rack (1.5.2) lib/rack/methodoverride.rb:21:in `call' 
rack (1.5.2) lib/rack/runtime.rb:17:in `call' 
activesupport (4.1.5) lib/active_support/cache/strategy/local_cache_middleware.rb:26:in `call' 
rack (1.5.2) lib/rack/lock.rb:17:in `call' 
actionpack (4.1.5) lib/action_dispatch/middleware/static.rb:64:in `call' 
rack (1.5.2) lib/rack/sendfile.rb:112:in `call' 
railties (4.1.5) lib/rails/engine.rb:514:in `call' 
railties (4.1.5) lib/rails/application.rb:144:in `call' 
passenger (4.0.50) lib/phusion_passenger/rack/thread_handler_extension.rb:74:in `process_request' 
passenger (4.0.50) lib/phusion_passenger/request_handler/thread_handler.rb:141:in `accept_and_process_next_request' 
passenger (4.0.50) lib/phusion_passenger/request_handler/thread_handler.rb:109:in `main_loop' 
passenger (4.0.50) lib/phusion_passenger/request_handler.rb:455:in `block (3 levels) in start_threads' 

я в основном просто пытаюсь узнать, как использовать проблемы с контроллерами. Я хочу отделить большой кусок моего кода и поставить его в соответствие с тем, чтобы держать контроллер в чистоте и чистоте.

Существует не так много, чтобы найти, когда искать или искать SO для проблем с контроллерами, поэтому я задал этот новый вопрос в надежде получить помощь.

Как можно устранить эту проблему и что я делаю неправильно?

ответ

8

У вас возник конфликт с именем - Data класс существует в основном рубине: link here. Это означает, что Rails не инициирует const_missing, и ваша проблема никогда не будет загружена. Переименуйте свою проблему в DateModule или sth.

+1

избил меня на 2 секунды :-) – Stefan

+0

Спасибо, просто понял, прочитав комментарии в предыдущем ответе тоже. Отлично работает сейчас :) – Kaspar

1

Вы сделали простую опечатку в отношении данных - это должно быть extend ActiveSupport::Concern (обратите внимание на двойной двоеточие, являющееся разделителем пространства имен в Ruby).

+0

Кажется, что это действительно опечатка, но даже после ее изменения: «Расширить ActiveSupport :: Концерн» Кажется, что у меня такая же ошибка. Перезагруженный веб-сервер также на всякий случай. – Kaspar

+0

У вас также есть класс под названием Data где-то в вашей системе? Например, модель? – sevenseacat

+0

Нет, это кажется единственным. – Kaspar

Смежные вопросы