views:

79

answers:

2

If I know the current_user's answers because the User model has an answers collection:

current_user.answers

How do I test whether that answers collection contains the current answer (referenced by the @answer class variable) at each step of a loop?

I was tempted to use the include? method:

current_user.answers.include?(@answer)

but I see it's for mixins :(

+3  A: 

You may be best off doing this in the database:

current_user.answers.exists?(@answer.id)

This will execute a select id from answers where id = ? and user_id = ? and return true if it exists.

If you already have answers loaded in memory, include? should work, or any?{|ans| ans.id == @answer.id} or flatten them all out into a set of ids outside the loop:

Set.new(current_user.answers.map(&:id)

and then test for id inclusion inside the loop.

cwninja
Awesome. Thanks, man!
Joe O'Driscoll
+1  A: 

All Enumerable collections (including Arrays, Hashes and Sets) have the include? method to test membership.

[1,2,3].include? 2 # => true
{foo: 'foo', bar: 'bar'}.include? :foo # => true
[1,2,3].include? 5 # => false

(There's also an include? method that modules have, but it's not the same thing.)

Chuck
Chuck: Thanks for clarifying the distinction.
Joe O'Driscoll