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
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
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
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