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

One Response to “Ensure has_one Instance Exists”


  1. 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


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.