active_record_upsert icon indicating copy to clipboard operation
active_record_upsert copied to clipboard

How to upsert associations?

Open hrdwdmrbl opened this issue 2 years ago • 1 comments

Example where there is a uniqueness constraint on Children's names

parent = Parent.new
parent.children.build(name: "Ken")
parent.save!

When the parent saves, it will auto-save the child. How can I upsert the child?

hrdwdmrbl avatar May 12 '22 11:05 hrdwdmrbl

A possible solution is to intercept the save method

def save(*args)
  upsert(*args)
end

This seems to work in my testing but it makes me very nervous!

hrdwdmrbl avatar May 12 '22 11:05 hrdwdmrbl