d3vkit
d3vkit

Reputation: 1982

Check if all children objects belong to same parent?

Rails 3.1, Ruby 1.8.7

I have Group, which :has_many => :items

I have Item, which :belongs_to => :group

Then, I sometimes run a search which returns many items - which may or may not all belong to the same group.

Is there a way to check in the view if all items in the returned array belong to the same parent (group)?

The best I can think of is this:

##Application Helper
def belongs_to_same_group(items)
  group = items.first.group
  items.each do |item|
    return false if item.group != group
  end
  return true
end

But I'm guessing ruby or rails has some great one-liner for these situations that I don't know about/am not skillful enough to think of.

Upvotes: 0

Views: 588

Answers (1)

numbers1311407
numbers1311407

Reputation: 34072

here's a one liner:

items.map(&:group_id).uniq.length == 1

or, another way to write what you already did:

items.all? {|item| item.group_id == items.first.group_id }

Upvotes: 2

Related Questions