populator
populator copied to clipboard
What to do when generating a model with double belongs_to ?
Let's say we have Book, Shelf and Author models. We can generate Authors and Books inside the loop, but how could we link Shelves?
Shelf.populate 20 do |shelf| shelf.name = Populator.words(1..3).titleize end Author.populate 40 do |author| Book.populate 0..40 do |book| book.author_id = author.id end end
Any idea or suggestion ?
I can see this is an old issue, yet still open. Here is my suggestion to the problem
Shelf.populate 20 do |shelf|
shelf.name = Populator.words(1..3).titleize
end
Author.populate 40 do |author|
Book.populate 0..40 do |book|
book.author_id = author.id
book.shelf_id = Shelf.offset(rand(Shelf.count)).limit(1)
end
end