populator icon indicating copy to clipboard operation
populator copied to clipboard

What to do when generating a model with double belongs_to ?

Open bmedici opened this issue 16 years ago • 1 comments

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 ?

bmedici avatar Jan 07 '10 14:01 bmedici

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

Tornskaden avatar Aug 01 '11 14:08 Tornskaden