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

Tagged: 

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

    Cloudy Point
    Keymaster

    QuestionQuestion

    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?

    #246757

    Cloudy Point
    Keymaster

    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
    

    Or

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

    Or more efficient way

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

    Source: https://stackoverflow.com/questions/47965637/get-random-record
    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.