This project is archived and is in readonly mode.

#1274 ✓ wontfix
Norman Clarke

Add magic encoding comment to generated files

Reported by Norman Clarke | October 26th, 2008 @ 09:49 PM | in 2.x

This patch adds support for :order => :random in ActiveRecord queries.

MySQL has a different syntax for ordering by random than SQLite and Postgres (RAND() as opposed to RANDOM()). If you develop and test on SQLite and deploy to MySQL, you usually need to include some kind of workaround if you want to do a query that selects random records.

Various Ruby solutions to this problem exist but have drawbacks:

  • Using a randomly generated offset only works well when you are pulling one random record and can require a query to count rows first. Ordering by random in the database is just as easy with one record or many, and can always be done in one query.

  • Selecting all the records into an array and shuffling it can be expensive if you want to randomly select against a large table, even if you just pull the ids. Using the database to do this is much faster and generates less garbage.

Conceptually this tiny patch makes :order work a little more like :conditions hash arguments, in that it abstracts away the underlying SQL. It makes ActiveRecord::Base delegate the formatting of the "ORDER BY" arguments to the various adapters. At the moment only the argument ":random" is handled specially; all other arguments are simply passed back unmodified.

Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

Tickets have moved to Github

The new ticket tracker is available at https://github.com/rails/rails/issues

Shared Ticket Bins

Attachments

Pages