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?
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:
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
UserandUserGroupandUserPermissions, you haveUser,User::GroupandUser::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:You can specify however many levels of namespacing as you want, so
User::Group::Permissionwould be possible.