Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to organize Rails models that are too fat?

It is good practice to shift logic from the controller into the model. But in any complex system, this invariably leads to a very large file even if a majority of the methods are one liners as per the Rails Way.

I've resorted to splitting up models into other modules and including them in the original model, for example, model_flags, model_validation, etc. Anyone has a better way?

like image 930
Jaryl Avatar asked Jan 01 '09 09:01

Jaryl


2 Answers

I realize this is a fairly old question and it's been marked as answered, but it still has good Google juice, so I figured it was worth adding to...

Rails 3 introduced ActiveSupport::Concern, which can be used to modularize behavior that's shared across models. Or, for that matter, to slim down models that have become too fat.

DHH himself provides a nice, succinct example gist here:

https://gist.github.com/1014971

like image 200
tjstankus Avatar answered Sep 27 '22 19:09

tjstankus


I wouldn't do this for a few reasons.

First you violate the assumption that things will be where they should be which is probably the biggest bonus to rails in the first place. A new person can walk onto your project and navigate it quite easily if you stick model stuff in your model. If you pull it out you just add a delay and some confusion particularly if the only logic for removing something to a module is to reduce the model size.

Second you gain almost nothing from it and you lose something. File size doesn't matter these days when almost all editors and IDEs ease the navigation pain of large files. Moving stuff to a module actually takes some of this modern ease away and will require you and your colleagues or future maintainers to jump around several more files while working on one model.

That said I suspect what the hardcore rails best practice posse will tell you is that if your model is that large and complex then your design is flawed and your model is probably representing several things that could be made into separate models rather than modules.

like image 37
srboisvert Avatar answered Sep 27 '22 20:09

srboisvert