I have a model, let’s say Cat, and I want to create a new model, Owner. A Cat has_one :owner, but when I created the Cat model, the Owner model didn’t yet exist.
Without resorting to backfilling the new Owner model for each Cat, I want to have an easy way so if I call @cat.owner.something, and @cat.owner doesn’t exist yet, it will call @cat.create_owner on the fly and return it.
I’ve seen this done a few different ways, but I am wondering what is the most Rails-esque way of tackling this, since I need to do this quite often.
I haven’t seen this done before but decided to give it a shot anyways.
I first aliased the association method
ownerin theCatmodel to keep a backup of the original method. I overrode theownermethod to call thebuild_ownermethod (returns a newOwnerobject through the association) if the original method returns nil. Otherwise, return theoriginal_owner_methodobject.So now if you call:
cat = Cat.firstAssuming it doesn’t have an owner, it will build a new Owner object when you call:
cat.owner.nameIt will return nil, but still build the owner object on the
cat.ownerpart of the chain without calling method_missing.