Search code examples
ruby-on-railspaperclipnested-attributes

Adding associated records while updating a record rails


 def upload_new_incident_attachments
    @attachments.each do |attachment|
        if record.new_record?
          record.images.build(attachment: attachment)
        else
          record.images.create(attachment: attachment)
        end
    end
end

Build the associated records will get automatically saved if the parent model gets created(while saving), The child attributes won't get saved if there are validation errors(both in child and parent), I don't know how to handle this while updating the parent model,

def update
   if record.update_attributes(incident_params)
     upload_new_record_attachments if @attachments
   end
end

If there are validation errors while creating the child record, the parent model updated already, Is there any way to update both in a single commit( create child record and updating parent record), Or any other ways


Solution

  • You can check if its parent model is valid before building or creating child associations

    def update
      # Assign attributes to the parent model
      record.assign_attributes(incident_params)
    
      if record.valid?
        # Builds or creates images only when there are no validation errors
        upload_new_record_attachments if @attachments
    
        # Now you can save it and make sure there won't be any validation errors
        record.save
      end
    end