【问题标题】:Rails: How do I cancel a save if before_update callback returns false?Rails:如果 before_update 回调返回 false,我如何取消保存?
【发布时间】:2011-03-05 09:29:22
【问题描述】:

我有一个具有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 控制台中尝试过的:

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> 

【问题讨论】:

    标签: ruby-on-rails ruby activerecord


    【解决方案1】:

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

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

    【讨论】:

    • 如何检查相应的数据库行是否在rails中发生了变化?
    • 如果 before_update 返回 false,我该如何防止对象被更改?
    • update_attributes 返回 false 所以它没有改变 :) 对于第二个我不认为有办法,但你可以在更新失败时重新加载你的对象
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多