views:

218

answers:

4

Hello,

How do I get a random record when using :group?

@paintings = Painting.all(:group => "user_id", :order => "created_at DESC")

This gives me the latest painting for each user. Now I would like to select a random painting from each user instead of the latest. The order of the paintings should still be the same, so that the user that have been the most active will get his/her random painting displayed first.

painting150 (user1)
painting200 (user2)
painting231 (user3)

Is this possible?

Best regards. Asbjørn Morell.

A: 
@painting = @paintings[rand(@paintings.size-1)]

(or paintings.count, dont know the right method yet)

Lichtamberg
Should I use this in my view?
atmorell
This example only returns one random image... Even if @paintings contains 100 records.
atmorell
A: 

Assuming you have MySQL, you can try:

@paintings = Painting.all(:group => "user_id", :order => "RAND()")
Swanand
This always returns the same record for each user, but in random order :/ I need to return a random painting for each user.
atmorell
A: 

you could do something like this but it will suffer as your number of records grow

@paintings = Painting.find(:all, :order => 'RAND()').map{ |i| i.user_id }.uniq
ErsatzRyan
Hmmm it seems like your example returns the user id for the latest painting.>> @paintings = Painting.all.map{ |i| i.user_id }.uniq Painting Load (46.6ms) SELECT * FROM `paintings` => [3, 4, 5, 6, 7, 8, 9, 10]
atmorell
+1  A: 

This answer is specific to Rails, but since you are using ActiveRecord, I am assuming it should be fine.

unique_paintings = []
@paintings.group_by(&:user_id).each do |user_id, paintings|
  unique_paintings << paintings[rand(paintings.size-1)]
end

unique_paintings.sort_by(&:created_at)

The group_by most certainly messes up the created_at sort you did in the query, so I did a sort_by as the last step. You might want to get rid of it in the query since you'll have to do it anyway here.

BigCanOfTuna