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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With