Ruby-on-Rails [SOLVED]: Get random record

Ruby-on-Rails [SOLVED]: Get random record

Home Forums Frameworks Ruby on Rails Tutorials Ruby-on-Rails [SOLVED]: Get random record


Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
  • #246756

    Cloudy Point


    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?


    Cloudy Point

    Accepted AnswerAnswer

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

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


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

    Or more efficient way

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

    Author: Manishh
    Creative Commons License
    This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.