简体   繁体   中英

In Rails 3.1 how can I check if any instances of a model's has_many association have changed?

In Rails 3.1 I know you can check if a given instance of a model object can be changed, but how would I check if any instances of a model's has_many association changed.

For example assume I have an Order that has many LineItems. LineItems get added to an Order and I want to be able to check if any of the Order's LineItems has changed. I suppose one way of doing it would be to loop through each of the LineItems in the Order model like so:

def line_items_changed?
  self.line_items.each do |item|
    if item.changed?
      return true
    else
      return false
    end
  end
end

but was curious if there was a built in or more efficient way.

Shorter solution:

def line_items_changed?
  line_items.any?(&:changed?)
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM