views:

37

answers:

1

I am trying to choose 5 distinct brands from among the cars that belong to my users. My current attempt is below (no approach to selecting at random).

@range = @user.cars.select('DISTINCT brand_id').limit(5)

How might I select these five random distinct brands? Thank you very much.

A: 

Although not very elegant, I might select all your distinct brands and then pick 5 at random. In this case, I expect your list of brands is not very large so the initial query shouldn't be too expensive.

brands = @user.cars.select('DISTINCT brand_id')
selection = 5.times.map{ Random.new.rand(0..brands.size) } # Random requires Ruby 1.9.2+
@range = []
selection.each { |rec| @range << brands[rec] }

This is untested code so apologies if I've mislead.

Warren
It seems to have an issue doing DISTINCT on @user.cars. It seems to work directly on a model but not on related records.
sscirrus