Rails 4:如何取消对“before_save"的保存打回来? [英] Rails 4: How to cancel save on a "before_save" callback?
本文介绍了Rails 4:如何取消对“before_save"的保存打回来?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有复杂的模型/表格.我不想重复记录,所以我想合并具有相似属性的记录.如何使用 before_save 回调取消保存"?这就是我的想法:
I have complicated models / forms. I don't want repeated records, so I want to merge records that have similar attributes. How would I cancel "save" using a before_save callback? This is what I'm thinking:
class ProductsColor < ActiveRecord::Base
before_save :check_for_similar_record
def check_for_similar_record
if ProductsColor.exist?(color_id: self.color_id, product_id: self.product_id)
# merge values with existing ProductsColor and stop self from saving
end
end
end
推荐答案
为了防止记录被保存,你应该简单地返回false
:
To prevent record from being saved, you should simply return false
:
def check_for_similar_record
if ProductsColor.exists?(color_id: self.color_id, product_id: self.product_id)
# merge values
false
else
true
end
end
这篇关于Rails 4:如何取消对“before_save"的保存打回来?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文