All,
My apologies if this is a little long-winded and stream of
consciousness-y :).
SUMMARY: Why do we extend ActiveRecord instead of mixing it in to our
model classes?
Been thinking about my app’s models and starting to want to build
something of a hierarchy. I have some commonality across 3 of my model
classes and I’d liek to aggregate the behavior in a superclass.
However, I am stuck with all of my models being descendants of AR. So
within my set of models, I can’t aggregate common behavior into a
superclass within that hierarchy since my DB tables (legacy) do not
reflect that hierarchical structure.
So I’ve been thinking about why the model relationship to AR is
extension and not composition (why do models extend AR instead of
include/mixin it). I can certainly agree with the idea that the essence
of a model class is that it’s an OR mapping, but if you mixed in the
OR-mapping-ness instead of forcing it through your one shot at
inheritance (extending AR), you would still have the freedom to have
more non-database concerns be addressed (like a model object hierarchy
that doesn’t map to your persistence layer).
Given the fact that model classes do extend AR, you can certainly create
“pure model” classes that then mixin the AR subclasses or delegate to
the AR subclasses to handle persistence and then you can have whatever
model object heirarchy you want. Which I guess makes sense since your
application model shouldn’t necessarily be bound so tightly to your
persistence layer. Another option is to mix in your common domain
behavior from a module (“interface”).
My thought is that the model side of Rails is sort of presented as
though you can handle everything within the constraints of being an AR
descendant, but in fact, the AR descendants are just a persistence
object layer.
It just feels like the persistence piece should be what is mixed in, not
the domain behavior.
Any thoughts?
Wes