Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can put that code into your 'lib' directory saving as find_random.rb</p> <pre><code>module FindRandom # pull out a unique set of random active record objects without killing # the db by using "order by rand()" # Note: not true-random, but good enough for rough-and-ready use # # The first param specifies how many you want. # You can pass in find-options in the second param # examples: # Product.random =&gt; one random product # Product.random(3) =&gt; three random products in random order # # Note - this method works fine with scopes too! eg: # Product.in_stock.random =&gt; one random product that fits the "in_stock" scope # Product.in_stock.random(3) =&gt; three random products that fit the "in_stock" scope # Product.best_seller.in_stock.random =&gt; one random product that fits both scopes # def find_random(num = 1, opts = {}) # skip out if we don't have any return nil if (max = self.count(opts)) == 0 # don't request more than we have num = [max,num].min # build up a set of random offsets to go find find_ids = [] # this is here for scoping # get rid of the trivial cases if 1 == num # we only want one - pick one at random find_ids = [rand(max)] else # just randomise the set of possible ids find_ids = (0..max-1).to_a.sort_by { rand } # then grab out the number that we need find_ids = find_ids.slice(0..num-1) if num != max end # we've got a random set of ids - now go pull out the records find_ids.map {|the_id| first(opts.merge(:offset =&gt; the_id)) } end end </code></pre> <p>and extend your model like that </p> <pre><code>class Car &lt; ActiveRecord::Base extend FindRandom def self.tag_nr self.random end end </code></pre> <p>Calling Car.tag_nr will give you an instance, but something is wrong with your code if you trying to create new instance using other same class instance.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload