iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🗂

Stop Putting All Your Rails Models Directly Under the models Directory

に公開

The content in the title is all there is to it.
Well, if I just leave it at that, people might tell me to just post it on Twitter...

Default placement for rails generate model <model_name>

I'm sure all you wise Rails engineers out there
are daily

rails generate model <model_name>
# or
rails g model <model_name> field:type...

generating Model files and migration files to add Models.
However, if you rely on this method,
the models directory quickly becomes cluttered. (Doesn't it?)

The following is a quote from "Organize Your Models | err.the_blog".
Even though this has been pointed out since the days of Rails 1.2, I still often see structures where models are created directly under models without any organization.

So, what should we do?

At the time of the article mentioned above (since it was around Rails 1.2), it seems it was necessary to register reference paths in config.load_paths.
However, in at least Rails 5.x and above, for example:

app/models/user/registration.rb

class User::Registration < ApplicationRecord
  devise :confirmable
end

By placing it under a directory like this and naming the class declaration in association with the directory and file name, it works perfectly.

Please try adopting this approach!

Discussion