Name Models in a Rails Application

I recently had a discussion with my friend who is also a RoR developer. We argued about how to manage Rails models. Personally, I like to leave only root models (for example, User, Article, Bill, etc.) in the default namespace, and dependent models go to the module (for example, User :: Profile, User :: Activity) with the root name with by which they are connected.

On the other hand, I saw many projects that had 100 models in the default namespace called user_profile, user_activity, etc. Judging by the development of Java (Spring), the java community tends to organize the class in packages and group them logically, which I find very attractive.

So, the question is, is there a drawback in grouping models in modules (except for additional ones: class_name in the definition of a relation) and are there any specific reasons why people usually don’t do this?

+7
source share
1 answer

Although the namespace has its advantages, it requires the addition of exceptions in all models. Foo :: Bar assumes the name of the bars table and is similar to bar_id for associations, whereas you can use foo_bars and foo_bar_id .

If you are really serious about this, you can see if there is an add-in that fixes this for you, or implement your own extension that does.

The only time I used namespaces is add-ons that should be used in third-party applications where I don't want to require model names at the root level, as that would be annoying. Additional efforts in this case are worth it.

If it bothers you to see 100+ model files without any grouping, you will probably be just as annoyed to see more than 100 tables without grouping, and, as a rule, you cannot fix something.

Controllers can be grouped quite naturally, but models are not so easy to place, at least not with ActiveRecord.

+4
source

All Articles