Rails:如果before_update回调返回false,如何取消保存?

Cha*_*ory 3 ruby activerecord ruby-on-rails

我有一个有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
Run Code Online (Sandbox Code Playgroud)

这是我在rails控制台中尝试的内容:

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> 
Run Code Online (Sandbox Code Playgroud)

Adr*_*fin 6

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

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