在Rails 3.1中,如何检查模型的has_many关联的任何实例是否已更改?

jkl*_*ina 2 ruby-on-rails has-many ruby-on-rails-3

在Rails 3.1中,我知道您可以检查是否可以更改模型对象的给定实例,但是如何检查模型的has_many关联的任何实例是否已更改.

例如,假设我有一个包含许多LineItem的Order.LineItems被添加到Order中,我希望能够检查Order的LineItems是否有任何变化.我想一种方法是循环遍历Order模型中的每个LineItem,如下所示:

def line_items_changed?
  self.line_items.each do |item|
    if item.changed?
      return true
    else
      return false
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

但是如果有内置或更有效的方式,我很好奇.

Har*_*tty 7

更短的解决方案:

def line_items_changed?
  line_items.any?(&:changed?)
end
Run Code Online (Sandbox Code Playgroud)