Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a over 100 models in my rails application, and just for organization, I'm dividing them into folders, all still under the main model folder, just to make it simpler to navigate on the project and see files that are related.

Is this a bad idea? What is the rails way to do this?

like image 288
rafamvc Avatar asked Jan 07 '11 01:01

rafamvc


2 Answers

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.

like image 186
vonconrad Avatar answered Nov 18 '22 04:11

vonconrad


For 100 models, it's practically a requirement. 100 models is noisy in one directory.

Try this to get an idea of the Rails Way (tm)

rails new MultiDirectoryExample
cd MultiDirectoryExample
rails generate scaffold User::Photo description:string

Watch the script output and view the generated files.

like image 28
pathdependent Avatar answered Nov 18 '22 05:11

pathdependent