0

I am trying to get random record with where. Is it possible to do it in rails? For example, I have this:

Post.where(available: 'true', approved:  "true").first

I want to get random record instead of the first one. If it's possible to do it, will it have an effect on the performance?

sawa
  • 165,429
  • 45
  • 277
  • 381
Krilo Max
  • 245
  • 1
  • 3
  • 13

1 Answers1

1

You can simply use .shuffle on active record relation which will return you an array.

Post.where(available: 'true', approved:  "true").shuffle.first

Or

Post.where(available: 'true', approved:  "true").sample

Or more efficient way

Post.where(available: 'true', approved:  "true").order("RANDOM()")
Manishh
  • 1,444
  • 13
  • 23
  • extending @Manishh answer, you can also pass a number to `sample` method to get any number of results. e.g. `.sample(3)` will return 3 random records – Abdullah Dec 25 '17 at 05:15
  • Thanks a lot. Do you know which way would be most efficient in terms of speed and performance? – Krilo Max Dec 26 '17 at 03:15
  • @KriloMax with order clause it will take less time as compare to other options. – Manishh Dec 26 '17 at 03:37
  • Wouldn't this ```Post.where(available: 'true', approved: "true").order("RANDOM()")``` result in pulling all the records? or should I do something like ```Post.where(available: 'true', approved: "true").order("RANDOM()").first``` – Krilo Max Dec 26 '17 at 03:43
  • yes that up to you how many records you want. you can use take to limit number of records. – Manishh Dec 26 '17 at 03:58