Rails 3 - Distinct and Random
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 selectin开发者_如何学Gog at random).
@range = @user.cars.select('DISTINCT brand_id').limit(5)
How might I select these five random distinct brands? Thank you very much.
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.
The code given in the question chooses five car brands that belong to one particular user. That's a pretty lucky user.
If we assume that you're trying to choose five brands at random from all the cars owned by at least one of your users, I think you want something like this:
Car.select("DISTINCT cars.brand_id").order("RANDOM()").joins(:user).limit(5)
That should work so long as Car has a belong_to relationship to User.
If you really want to limit the scope to just a single user's cars, then you want something like this:
@user.cars.select("DISTINCT cars.brand_id").order("RANDOM()").limit(5)
For what it's worth, in mysql you need "order(RAND())" rather than "order(RANDOM())".
This will helps you picking distinct records
@range = @user.cars.select('brand_id').uniq.limit(5)
精彩评论