Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 597
bigpotato Avatar asked Jun 05 '14 16:06

bigpotato


1 Answers

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.

like image 180
Jorge de los Santos Avatar answered Sep 28 '22 17:09

Jorge de los Santos