【问题标题】:Rails: How should I run my associated objects' callbacks before the parent's callbacks?Rails:我应该如何在父回调之前运行关联对象的回调?
【发布时间】:2011-04-27 10:52:10
【问题描述】:

我有一个Invoice 模型,它是has_many :line_items

两个模型都有before_validation 回调。发票的回调要求首先运行行项目的回调。但是,默认情况下会运行发票的回调,然后运行每个行项目的回调。

有没有一种好的方法可以确保先验证行项目,然后验证发票?

目前,我正在玩这样的事情:

class Invoice < ActiveRecord::Base
  before_validation :do_something
  ...

private
  def do_something
    line_items.each { |line_item| line_item.run_callbacks(:validation) }
    # Then do whatever I need here - I've forced the callback order
  end
end

有没有更好的方法来处理这个问题?

【问题讨论】:

    标签: ruby-on-rails-3 activerecord callback activemodel


    【解决方案1】:

    检查它们是否有效

    def do_something
      line_items.all?(&:valid?)
      # Then do whatever I need here - I've forced the callback order
    end
    

    【讨论】:

    • 谢谢,这样更好。看到你不知道的 Ruby 细节总是很高兴!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-22
    • 2015-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多