This seems like an incredibly simple problem however it isn't working out as trivially as I'd expected.
I have a club which has club members and I'd like to pull out two members at random from a club.
Using RANDOM()
One way is to use random ordering:
club.members.find(:all, :order => 'RANDOM()').limit(2)
However that is different for SqLite (the dev database) and Postgres (production) since in MySql the command is RAND()
.
While I could start writing some wrappers around this I feel that the fact that it hasn't been done already and doesn't seem to be part of ActiveRecord tells me something and that RANDOM may not be the right way to go.
Pulling items out directly using their index
Another way of doing this is to pull the set in order but then select random records from it:
First off we need to generate a sequence of two unique indices corresponding to the members:
all_indices = 1..club.members.count
two_rand_indices = all_indices.to_a.shuffle.slice(0,2)
This gives an array with two indices guaranteed to be unique and random. We can use these indices to pull out our records
@user1, @user2 = Club.members.values_at(*two_rand_indices)
What's the best method?
While the second method is seems pretty nice, I also feel like I might be missing something and might have over complicated a simple problem. I'm clearly not the first person to have tackled this so what is the best, most SQL efficient route through it?