Rails: Getting random product within several categories -


I have a question about random entries in Rail 3. I have two models:

  class product & lt; ActiveRecord :: Base is_to: Category self.random Product.find: first,: offset = & gt; (ProductCount * ActiveSupport :: SecureRandom.random_number) .to_i End and Class Category & lt; ActiveRecord :: Base has_many: products end   

I am able to obtain a random product within all products using a random offset cast for Int. But I also want to be able to get random products within the given categories. I tried to do something like this, but due to the offset index it does not work:

  class product & lt; ActiveRecord :: Base is_to: Category includes self.random cat = {"Mac", "windows"] (categories). Where (: categories = & gt; {: name = & gt; cat}). Where (: First ,: offset => (ProductCount * ActiveSupport :: SecureRandom.random_number) .to_i) End End   

Anyone who knows better solution here?

thx! Tux

You can try it a bit more:

  class Product & lt; ActiveRecord :: Base DF self.random (cat = zero) cat || =% W [MAC Windows] includes (: Categories). SAME (: Categories = & gt; {: name = & gt; CAT}) Offset (Active:: SecureRendam.Rand_Number (Self Coat). First End & / Code>  

Many convenient accessory methods such as offset and first in Rail 3 that give you the where section The number of arguments can be reduced.

If there is a problem connecting with you, where there is a number of similar products Compared to the number of total products, you need to use the ORDER BY RAND () In most cases this is not really a great deal performance and you can always be sure that this is your Works for.

Comments