Ensure has_one Instance Exists
May 20, 2009
Sometimes you want to ensure that a has_one relationship always exists, even if the relationship is added after existing instances have already been created in your database. One way to solve the problem is to add an after_create and then have a rake task go through your database and create instances in each case where the has_one instance doesn’t yet exist.
I think the following is more elegant:
has_one :thing
def thing_with_create
thing_without_create || create_thing
end
alias_method_chain :thing, :create
I can then access o.thing and it will automatically create it if it doesn’t exist.
What do you think?
Advertisement





June 17, 2009 at 10:07 pm
You might like this plugin/gem I created for this pattern. I extracted the behavior from an application that has 14 has_one relationships on one model!
http://github.com/jqr/has_one_autocreate