Rails select random record

前端 未结 8 1760
佛祖请我去吃肉
佛祖请我去吃肉 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:04

    We found that offsets ran very slowly on MySql for a large table. Instead of using offset like:

    model.find(:first, :offset =>rand(c))
    

    ...we found the following technique ran more than 10x faster (fixed off by 1):

    max_id = Model.maximum("id")
    min_id = Model.minimum("id")
    id_range = max_id - min_id + 1
    random_id = min_id + rand(id_range).to_i
    Model.find(:first, :conditions => "id >= #{random_id}", :limit => 1, :order => "id")
    
    0 讨论(0)
  • 2020-12-03 04:06

    If you would need a random record but only within certain criteria you could use "random_where" from this code:

    module ActiveRecord
      class Base
        def self.random
          if (c = count) != 0
            find(:first, :offset =>rand(c))
          end
        end
    
        def self.random_where(*params)
          if (c = where(*params).count) != 0
            where(*params).find(:first, :offset =>rand(c))
          end
        end
    
      end
    end
    

    For e.g :

    @user = User.random_where("active = 1")
    

    This function is very useful for displaying random products based on some additional criteria

    0 讨论(0)
提交回复
热议问题