List random objects

0

How could I generate random cars in the following model?
would it be better to do this in the controller?

class Pessoa < ActiveRecord::Base
       has_many :carros
end
    
asked by anonymous 26.09.2016 / 15:44

2 answers

0

You can make a scope to bring these cars randomly. It looks something like this:

class Pessoa < ActiveRecord::Base
  has_many :carros
end



class Carro < ActiveRecord::Base
  belongs_to :pessoa
  scope :aleatorios, -> { limit(5).order('RANDOM()') }
end

Where 5 in limit is the amount of carros you want to return.

So you can do, for example:

pessoa = Pessoa.first
pessoa.carros.aleatorios

GG WP

    
27.09.2016 / 13:44
1

Thanks for the answer I did + or - what you just spent in the class Car < ActiveRecord and I called the method in the view like this:

class Carro < ActiveRecord::Base 

    class << self def carro_random(n=4) 
        self.order('rand()').first(n) 
      end 
    end 
end
    
27.09.2016 / 15:15