0
How could I generate random cars in the following model?
it would be better to do this in controller?
class Pessoa < ActiveRecord::Base
has_many :carros
end
0
How could I generate random cars in the following model?
it would be better to do this in controller?
class Pessoa < ActiveRecord::Base
has_many :carros
end
1
thanks for the reply I did + or - what Voce spent only in the class Car < Activerecord and called the method in the view that way:
class Carro < ActiveRecord::Base
class << self def carro_random(n=4)
self.order('rand()').first(n)
end
end
end
0
You can make a Scope to bring these cars in 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 the limit
is the amount of carros
that you wish to be returned.
So you can do, for example:
pessoa = Pessoa.first
pessoa.carros.aleatorios
GG WP
Browser other questions tagged ruby random active-record rails4
You are not signed in. Login or sign up in order to post.