我正在调用@foo.update
,并在要更新的属性1的内部,正在def attribute=
的模型类中调用write方法(foo
),并希望它有条件地使整个更新失败。我可以放什么东西?我尝试使用errors[:base]
,但它不会使save
失败。我也不能使用validates
,因为该属性在保存之前会被转换成其他东西。
def attribute=(attr)
if bar
# code to fail entire db save
end
end
最佳答案
您可以只检查before_save
模型中foo.rb
回调上的条件,如果不想保存,则返回false。
before_save :really_want_to_save?
private
def really_want_to_save?
conditional_says_yes ? true : false
end
如果您也想要错误消息,那么
def really_want_to_save?
if conditional_says_yes
true
else
errors[:base] << "failed"
false
end
end
关于ruby-on-rails - 手动失败#update_attributes保存在Rails中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44336900/