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

I have Purchasethat 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 just like to grab the existing shipping_address attached to the purchase, if it exists, and not always create a new replacement (which, I believe, removes the old one and creates a new one in the database).

Is there a way to do it purchase.first_or_build_shipping_address(...)in Rails?

+4
source share
1 answer

Try the following:

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

As long as the first returns zero, you will create a new one.

+2
source

Source: https://habr.com/ru/post/1543443/


All Articles