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

后端 未结 2 979
天命终不由人
天命终不由人 2021-01-30 04:34

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 n

相关标签:
2条回答
  • 2021-01-30 04:49

    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.

    0 讨论(0)
  • 2021-01-30 05:07

    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.

    0 讨论(0)
提交回复
热议问题