开发者

Rails 3 namespacing requires model to be defined twice?

I'm pulling m开发者_运维百科y hair out trying to understand namespacing in Rails 3. I've tried following a few different tutorials, and the only way I can get my models to work is if I define my model in both the base directory and my namespace directory.

If I only define the model in the namespace directory it expects it to define both Model and Namespace::Model, as below:

LoadError (Expected .../app/models/plugins/chat.rb to define Chat):

or

LoadError (Expected .../app/models/plugins/chat.rb to define Plugins::Chat):

I'm sure I'm missing something obvious, but I could really use a pointer in the right direction. Here are the relevant excerpts.

/models/plugins/chat.rb

class Plugins::Chat
  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming
...
end

/controllers/plugins/chats_controller.rb

class Plugins::ChatsController < Plugins::ApplicationController
load_and_authorize_resource
...  
end

/config/routes.rb

namespace :plugins do 
  resources :chats
end

/config/application.rb

config.autoload_paths += Dir["#{config.root}/app/models/**/"]

Edit This is some kind of bad interaction with CanCan, the gem we're using for permissions. The line load_and_authorize_resource is somehow at fault. Will keep digging...


I noticed a reference to load_and_authorize_resource in your controller. This method is used by the CanCan gem to create an instance of your model and then test if the user has access to it. If you are using a namespaced model you will need to specify the class:

class Plugins::ChatsController < Plugins::ApplicationController
load_and_authorize_resource :class "Plugins::Chat"
...  
end


It sounds like at some point you're referencing the Chat constant \by itself before it's loaded. Rails then tries to find that by looking at models/chat.rb, can't find it, and complains. Check your constant usage (the backtrace should tell you where it's being invoked from), and clean it up, and Rails should be less complain-y.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜