Rails 4: Is there a first_or_initialize for a has_one association?

ruby-on-rails

Solution

Try this:

@shipping_address ||= purchase.shipping_address || purchase.build_shipping_address

As long as the first one returns nil you will be creating a new one.

Problem

I have a `Purchase` that `has_one :shipping_address`. In one of my methods I have this: ``` @shipping_address ||= purchase.build_shipping_address( first_name: shipping_address_first_name, ... ) ``` However, I would like to just grab the existing shipping_address attached to the purchase if it exists instead of always creating a new replacement (which I believe deletes the old one and creates a new one in the database). Is there a way to do `purchase.first_or_build_shipping_address(...)` in Rails?

Original source