jklina
jklina

Reputation: 3417

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.

Upvotes: 2

Views: 1509

Answers (1)

Harish Shetty
Harish Shetty

Reputation: 64363

Shorter solution:

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

Upvotes: 7

Related Questions