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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With