1

So, I'd like to do some random ordering when displaying data the code I have at this point is:

Timsheet.limit(1).offset(RANDOM(Timesheet.count)).first

I know that postgresql's (RANDOM) syntax is different than MYSQL's (RAND()) and Oracles (dbms_random.value) syntax.

I'd just like to confirm that my code is correct, from what I understand it's doing is, it's grabbing the first row, and offsetting the data in a random order?

Please help clear this up, thanks!

user3399101
  • 1,477
  • 3
  • 14
  • 29
  • 1
    I think you want `Timsheet.order('RANDOM()').first`: This will make a random order and select the first record: *in fine* you get one random record. --- Using your code (with offset) always returns the same record in my IRB console – MrYoshiji May 13 '14 at 14:49
  • You should be able to see, in your log, what sql is generated from your ruby code: that's always a good sanity check. Looking at it, i would say that it will grab a random timesheet record from the table. – Max Williams May 13 '14 at 14:50
  • 2
    Actually maybe not. See this question: http://stackoverflow.com/questions/5297396/quick-random-row-selection-in-postgres – Max Williams May 13 '14 at 14:52

1 Answers1

1

I think the following will work with all DBMS's

Timsheet.offset(Random.new.rand(Timsheet.count)).first
Ruby Racer
  • 5,690
  • 1
  • 26
  • 43