Choose 6 records from the database randomly

Hello All,

I have to choose 6 records from the table but randomly.
I have written the code:
@products = Product.find(:all, :conditions => “feature = 1”, :limit =>
6)
But it fetches only the first six records from the table. I want to
choose only 6 products but in random order not the first six.

Please tell me how to implement it.
Any help would be greatly appreciated.

Thanks,
Rohit.

Get all the product ids:
ids = Product.find(:all, :select => :id).map(&:id)

Choose six at random"
random_ids = … # left as an exercise for the reader

@products = Product.find(random_ids)

On Dec 4, 6:58 am, kevin cline [email protected] wrote:

Get all the product ids:
ids = Product.find(:all, :select => :id).map(&:id)

Choose six at random"
random_ids = … # left as an exercise for the reader

That will be incredibly inefficient. ‘Select * from products order by
rand() limit 6’ is also not massively fast.

One fast way of doing this (which happens to be the way wikipedia does
their random article search):
assign to every product a random number between 0 and 1

When you want to get some random products, then pick a random number
and select the products whose random value is great than the number
you’ve just picked. If you’ve got an index on the column, this should
be pretty speedy.

Fred

Hi Fred,

Sorry…am not able to understand what you have written.
How to assign a random number between 0 to 1 to a product?
Could you please explain?

Thanks,
Rohit.

On Dec 4, 2007 9:18 AM, Rohit M. [email protected]
wrote:

Hi Fred,

Sorry…am not able to understand what you have written.
How to assign a random number between 0 to 1 to a product?
Could you please explain?

Well you have a column on the products table that contains a random
number.

Fred

You could use custom SQL SELECT … FROM my_table ORDER BY RAND()
LIMIT (N)

On Dec 4, 6:43 am, Rohit M. [email protected]

He Fred, that’s a slick idea. I was mulling over the best way to do
this – in the course of programming an online game, I needed to pick
n contestants from a pool of arbitrary size, then narrow that to n/2
contestants, then n/4, finally ending up with just one.

Adding and indexing a random number beforehand sounds like a good way
to go. Thanks for the thought!

Really cool …

On Dec 4, 4:59 pm, Frederick C. [email protected]

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs