0

Ignoring the inefficiency of the query is there an existing Rails wrapper for abstracting the differences between rand() across databases?

MySQL:

User.first(order: 'random()')

Postgres:

User.first(order: 'rand()')

I can create my own constant RAND_STR but was wondering if one already existed?

Please note - this is not an efficiency question

I know the query is inefficient I'm just wondering about the abstraction

Peter Nixey
  • 16,187
  • 14
  • 79
  • 133

2 Answers2

0

You could so something like User.offset(rand(User.count)).first, but that would wind up executing two queries. Other than that, Rails doesn't have any built-in way to do this that I know of.

See Rails 3: Get Random Record

Community
  • 1
  • 1
Dylan Markow
  • 123,080
  • 26
  • 284
  • 201
  • Thanks - it's not how to get a random record I'm interested in though it's whether there's a Rails variable that stores the correct form of rand/random for the underlying database – Peter Nixey Jan 17 '12 at 16:29
  • Not that I'm aware of; the rails docs show nothing about random records. – Dylan Markow Jan 17 '12 at 16:31
0

I'm sure I used to have this problem however now it seems to have disappeared. Both SQLlite and Postgres are accepting RANDOM(). Not sure whether this is Rails' handiwork but whatever the reason it is now fixed.

Peter Nixey
  • 16,187
  • 14
  • 79
  • 133