Check if all children objects belong to same parent?
Rails 3.1, Ruby 1.8.7
I ha开发者_开发问答ve 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.
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 }
精彩评论