choose 6 records from the database randomly

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)

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

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

Fred

Really cool ...

For small tables, ‎`ORDER BY RAND() LIMIT 6` is fine, but it sorts the whole set and gets painful at scale. A practical approach is to choose a strategy based on database and table size: on PostgreSQL, ‎`TABLESAMPLE BERNOULLI` avoids full sorts; on MySQL/SQLite, an efficient offset-based sample is faster than shuffling the entire table. If you want this wired into ActiveRecord, RandomRails adds ‎`Model.random(count: 6)` and composes with scopes, picking the right strategy under the hood. Code and benchmarks here: https://github.com/the-rubies-way/random-rails :up_right_arrow:

You can use SQL here by doing Product.order(‘RANDOM()‘).limit(6)