2011-03-05 80 views
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> 

回答

6

只有Ruby对象发生了变化。检查相应的数据库行是否已更改 - 它不应该有。

Rails验证不会阻止对象属性发生更改,它会阻止它们保存到数据库。

+0

如何检查相应的数据库行是否在rails中更改? – Chanpory 2011-03-05 09:42:37

+0

如果before_update返回false,我该如何防止对象被更改? – Chanpory 2011-03-05 09:43:03

+0

update_attributes返回false所以它没有改变:)对于第二个我不认为有办法,但你可以重新加载你的对象,当更新失败 – 2011-03-05 09:47:12

相关问题