在 Rails 上注册多个 before_save 条件回调 4

Register multiple before_save conditional callbacks on Rails 4

我有两个不同的计算要在我的模型上针对两个不同的领域进行。保存前。

Class Event < ActiveRecord::Base
  #some relations
  before_save :method1, unless: :some_field_1?
  before_save :method2, unless: :some_field_2?

  def method1
    some_field_1 = some_other_field / 2
  end

  def method2
    some_field_2 = some_field_1 / 3
  end
end

我遇到的问题是调用 method2 时 some_field_1 为空。我的猜测是像我这样声明 before_save 回调是错误的。

我知道我可以在没有条件和问题解决的情况下将这两种方法合二为一,但我更愿意有条件回调。我想知道正确的做法。文档对此不是很清楚。

非常感谢!

编辑

供日后参考。代码没问题。问题出在其他地方(数据库)!

您可以在同一个过滤器上调用它们,以逗号分隔。

例如:

before_validation :t1, :t2

def t1; puts "t1"; end    
def t2; puts "t2"; end

在我的测试中似乎是按这个顺序执行的。

此外,来自文档 (http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html):

Canceling callbacks

If a before_* callback returns false, all the later callbacks and the associated action are cancelled. If an after_* callback returns false, all the later callbacks are cancelled. Callbacks are generally run in the order they are defined, with the exception of callbacks defined as methods on the model, which are called last.

如果您想在 before_save 之前完成某些事情,您可能需要设置在它之前触发的过滤器之一,例如 after_validation,例如,做这些工作。

Does the second before_save overrides the first?

没有

Does the callbacks are executed in the same order in which they are declared?

由于您的属性不是布尔值,您可能不应该使用问号。尝试:

before_save :method1, unless: :some_field_1
before_save :method2, unless: :some_field_2