开发者

Random jokes in a skit (activerecord)

开发者 https://www.devze.com 2023-01-19 21:32 出处:网络
I am working on populating my database with test data using populate.rake: Repertoire.includes(:jokes).each do |r|

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消