Random jokes in a skit (activerecord)
I am working on populating my database with test data using populate.rake:
Repertoire.includes(:jokes).each do |r|
@jokes = r.jokes
Skit.populate 8..12 do |skit|
skit.joke_id = @jokes[rand(@jokes.count)].id
end
e开发者_StackOverflownd
This is giving me a RuntimeError: Called id for nil.
How can I populate a skit with random jokes?
sort_by {rand}
should sort your array of jokes.
Or, there is also doing an .order("rand()/random()")
(depending on your db) in your Repertoire query and putting a limit on the query.
Not sure if this will fix your problem but Ruby has a rand
method for arrays so you should be able to call @jokes.rand.id
instead. Seems like that would simplify things and maybe even fix your error.
精彩评论