James Pearson
James Pearson

Reputation: 1672

Ruby on Rails: testing if ActiveRecord results include a value

Afternoon,

Lets say I have gather a random selection of users:

User.find(:all, :limit => 10, :order => "rand()")

Now from these results, I want to see if the user with the ID of 3 was included in the results, what would be the best way of finding this out?

I thought about Array.include? but that seems to be a dead end for me.

Thanks

JP

Upvotes: 10

Views: 5791

Answers (3)

runako
runako

Reputation: 6152

User.find(:all, :limit => 10, :order => "rand()").any? { |u| u.id == 3 }

This will save you from doing another find.

Upvotes: 0

Chuck
Chuck

Reputation: 237010

users = User.find(:all, :limit => 10, :order => "rand()")
users.any? {|u| u.id == 3}

Upvotes: 10

Alex Wayne
Alex Wayne

Reputation: 187004

assert random_users.include?(User.find 3), "Not found!"

Active record objects are considered equal if they have equal ids. Array#include? respects the objects defined equality via the == method.

Upvotes: 4

Related Questions