Rails select random record

前端 未结 8 1764
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-03 03:46

I don\'t know if I\'m just looking in the wrong places here or what, but does active record have a method for retrieving a random object?

Something like?

<         


        
8条回答
  •  抹茶落季
    2020-12-03 04:01

    In Rails 4 I would extend ActiveRecord::Relation:

    class ActiveRecord::Relation
      def random
        offset(rand(count))
      end
    end
    

    This way you can use scopes:

    SomeModel.all.random.first # Return one random record
    SomeModel.some_scope.another_scope.random.first
    

提交回复
热议问题