我想使用回调检查是否有重复的记录的accepts_nested_attributes_for参数,并在满足条件时更新而不是创建。
这可能吗?
我尝试过的事情:
before_validation :update_instead
def update_instead
unless self.id
existing_provision = Provision.where(survey_id: self.survey_id).where(service_id: self.service_id).first
if existing_provision
self.id = existing_provision.id
end
end
end
这不起作用,因为它只是尝试创建具有ID设置的记录,这显然会触发具有重复ID的错误。
答案 0 :(得分:0)
据我所知,您可以为此目的使用find_or_create_by
provision = Provision.find_or_create_by(survey_id: self.survey_id, service_id: self.service_id)
provision.update(foo: bar)