我有一个具有before_update
回调的模型。根据我的理解,在模型实例上调用before_update
时会调用update_attributes
。我的假设是,如果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
这是我在rails console中尝试的内容:
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>
答案 0 :(得分:6)
只有Ruby对象发生了变化。检查相应的数据库行是否已更改 - 它应该没有。
Rails验证不会阻止对象属性发生更改,它会阻止它们保存到数据库中。