更新记录时添加关联记录 rails
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
如果创建父模型(保存时),构建关联记录将自动保存,如果存在验证错误(子和父),子属性将不会保存,我不知道如何在更新父模型时处理此问题,
def update
if record.update_attributes(incident_params)
upload_new_record_attachments if @attachments
end
end
如果在创建子记录时出现验证错误,父模型已经更新,有没有办法在一次提交中同时更新(创建子记录和更新父记录),或者任何其他方式
您可以在构建或创建子关联之前检查其父模型是否有效
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
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
如果创建父模型(保存时),构建关联记录将自动保存,如果存在验证错误(子和父),子属性将不会保存,我不知道如何在更新父模型时处理此问题,
def update
if record.update_attributes(incident_params)
upload_new_record_attachments if @attachments
end
end
如果在创建子记录时出现验证错误,父模型已经更新,有没有办法在一次提交中同时更新(创建子记录和更新父记录),或者任何其他方式
您可以在构建或创建子关联之前检查其父模型是否有效
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