Reputation: 3516
I want to check the existence of any HABTM relationships in an array and return true if any exist.
At present, the only way I can see to do this is:
result = false
[1,2,3,4].each do |i|
if user.parents.exists?(i)
result = true
break
end
end
I tried passing in an array as follows, but I get an exception
result = true if user.parents.exists?([1,2,3,4])
NoMethodError: undefined method `include?` for 1:Fixnum
Is there a better way of doing this?
Upvotes: 3
Views: 2191
Reputation: 15788
[1,2,3,4].inject(false) {|res, i| res ||= user.parents.exists?(i)}
Pretty much the same logic, just more ruby-ish code using inject syntax.
UPDATE:
Haven't tested it. but this might also work:
user.parents.exists?(:id => [1,2,3,4])
Upvotes: 4