I’ve been working on a project at nVisium that has records (of the ActiveRecord kind) with attributes that are themselves a stored domain object. Until recently, I would have probably done one of three things (in decreasing likelihood) to handle this situation:
- Use serialization to store the attributes of the domain object in JSON, then wrap the AR object in a decorator to handle translations from the “bag of data” to my domain, even though it means doing the ActiveModel dance to allow me to use this object in a form, and ActiveRecord will always see this attribute as “changed”, meaning unnecessary database operations.
- Come up with some convoluted way to represent this data using ActiveRecord
associations, even though it would almost certainly mean I’d find myself
has_onesomewhere (ick), and probably still wrapping the whole thing up to avoid using
- Gone the polyglot persistence route, even though it would mean taking on the ongoing operational overhead of managing another storage backend.
Thankfully, in Rails 5, the ActiveRecord Attributes API offers a fourth option, and it’s much nicer. Even better, we can already use this functionality in Rails 4.2. Head on over to my post on the nVisium blog to read how.comments powered by Disqus