3
我有一个模型,它有一个before_update
回调。根据我的理解,在模型实例上调用update_attributes
时调用before_update
。我的假设是,如果before_update
回调返回false
该记录将不会更新。Rails:如果before_update回调返回false,我如何取消保存?
但是,这看起来并不像按假定的那样工作。每次我拨打update_attributes
时,即使before_update
返回false
,记录也会被保存。如果before_update
返回false
,您是否知道如何防止记录被更新?下面是我在user.rb文件已经试过:
class User < ActiveRecord::Base
validates :first_name, :last_name, :presence => true
before_update do
false
end
end
这是我在轨控制台已经试过:
u = User.new(:first_name=>"John", :last_name => "Doe")
=> #<User id: nil, first_name: "John", last_name: "Doe", created_at: nil, updated_at: nil>
u.update_attributes(:first_name=>nil)
=> false
u.changed?
=> true
u
=> #<User id: nil, first_name: nil, last_name: "Doe", created_at: nil, updated_at: nil>
如何检查相应的数据库行是否在rails中更改? – Chanpory 2011-03-05 09:42:37
如果before_update返回false,我该如何防止对象被更改? – Chanpory 2011-03-05 09:43:03
update_attributes返回false所以它没有改变:)对于第二个我不认为有办法,但你可以重新加载你的对象,当更新失败 – 2011-03-05 09:47:12