开发者

Should models be namespaced in Rails?

Usually there are a lot of models in a Ruby on Rails project, so:

  1. Is it a good practice to namespace them (in modul开发者_如何学Goes/folders)? What are the downsides? EG:

    • Shop
      • category.rb
      • details.rb
    • Products
      • category.rb
      • base.rb

    etc

    (instead of ShopCategory, to have Shop::Category?)

  2. Should also the controllers be namespaced in the same manner?


I've recently found this post but back from 2007 by Pratik Naik. Says there namespace in models doesn't really resemble databases. Uses something like below. Even there's a quote from DHH too.

Rails::Initializer.run do |config|
  # Your existing stuff
  config.load_paths << "#{RAILS_ROOT}/app/models/pets"
end

http://m.onkey.org/2007/12/9/namespaced-models

p/s: I don't know whether the post is still relevant or not, just something I found recently when I wanted namespaces in my models.


I'm doing that a lot.
So yes I think that's something you should do.

It'll be be a lot easier for you to view models if you have them subdivided in subdirectories instead of having them all in the same one.

The same recommendation is also valid for your controllers and your views.


I recommend using single table inheritance for your category model. For example:

Category < ActiveRecord::Base end

ShopCategory < Category end

ProductCategory < Category end

Shop < ActiveRecord::Base
  belongs_to :shop_category
end

Product < ActiveRecord::Base
  belongs_to :product_category
end

This will encapsulate commonly used category behaviour and attributes into a single model and could allow you to reuse a lot of code and have a single controller. Using namespacing only makes sense to me when the underlying classes have some sort of data/functionality in common. (example: acts_as_versioned creates a Version class namespaced under the model)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜