Is it a bad idea do divide the models into directories?

No, it’s not a bad idea. Many people do it and I couldn’t live without it in large applications.

There are two ways of doing it:

The first is to just move your models. You will, however, have to tell Rails to load the wayward models (as it won’t know where they are). Something like this should do the trick:

# In config/application.rb
module YourApp
  class Application < Rails::Application
    # Other config options

    config.autoload_paths << Dir["#{Rails.root}/app/models/*"]
  end
end

The first way is easy, but is not really the best way. The second way involves namespacing your models with groups they’re in. This means that instead of having User and UserGroup and UserPermissions, you have User, User::Group and User::Permission.

To use this, generate a model like this: rails generate model User::Group. Rails will automatically create all of the folders for you. An added benefit is that with this approach, you won’t have to spell out the full model name for associations within a namespace:

class User < ActiveRecord::Base
  belongs_to :group # Rails will detect User::Group as it's in the same namespace
end

class User::Group < ActiveRecord::Base
  has_many :users
end

You can specify however many levels of namespacing as you want, so User::Group::Permission would be possible.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)