
Last night, found a problem in codes during updating form for a has_many relationship model. Rather than updating the record, it created a new one.
The solution is in railscasts episode 75.
Consider contact that has_many contact_email addresses. Created
def contact_email_attributes=(contact_email_attributes) contact_email_attributes do |attributes| contact_emails.build(attributes) end end
Changed to this one:
def contact_email_attributes=(contact_email_attributes) contact_email_attributes.each do |attributes| if attributes[:id].blank? contact_emails.build(attributes) else contact_email = contact_emails.detect { |e| e.id == attributes[:id].to_i } contact_email.attributes = attributes end end end
that will updates contact_email if there’s :id attributes. Then, I need to add the :id inside the form as hidden_field_tag:
- @contact.contact_emails.each do |contact_email| ... = hidden_field_tag "contact[contact_email_attributes][][id]", contact_email.id ...
And that’s all. It’s done.
In the form, you could do fields_for rather than using _tag methods. In fact, my original code was using that but after I tried everything and it ended up with the _tag methods, I was lazy to change it back. By the way, it works both ways…




Leave a Reply