ruby-on-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
推荐阅读
- php - bigquery php 客户端不适用于 Apache 网页(Ubuntu 18.10 服务器)
- excel - Excel VBA - 计算筛选表的行数。继续得到 4 而不是 0
- javascript - 带切换按钮的角度动画
- node.js - 尝试为推送通知注册 PUSH 时出现 DOMException 错误
- react-native - React Navigation v 2 和 Redux
- mysql - MySQL:枚举和计数
- android - Android导航组件弹出过渡问题
- google-oauth - 需要以前的答案无法解决此问题以解决 redirect_uri_mismatch
- shell - 如何隐藏shell命令的信息将打印并保存到变量中?
- sql - 游标不包括结果中的第一个 select 语句