Using the ActiveRecord Attributes API

Comments

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:

  1. 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.
  2. Come up with some convoluted way to represent this data using ActiveRecord associations, even though it would almost certainly mean I’d find myself using has_one somewhere (ick), and probably still wrapping the whole thing up to avoid using accepts_nested_attributes_for in forms.
  3. 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