Rails: Accessing previous loop in Populator (rake db:populate)

Posted by sscirrus on Stack Overflow See other posts from Stack Overflow or by sscirrus
Published on 2010-06-11T23:43:46Z Indexed on 2010/06/11 23:53 UTC
Read the original article Hit count: 273

Filed under:
|
|
|
|

I am populating my Rails database using populator, and I have a case where I would like to build a series of records where fields start_date and end_date follow seamlessly from each other (from today back into the past).

Here is a sample of what I'm doing:

Chain.populate 1 do |ch|
  ch.date_end = DateTime.now
  ch.date_start = DateTime.civil(DateTime.now.year-rand(40)-1, rand(12)+1, rand(31)+1)
end
Chain.populate 0..10 do |chs|
  chs.date_end = Chain.find(:last).date_start
  chs.date_start = DateTime.civil(chs.date_end.year-rand(10)-1, rand(12)+1, rand(31)+1)
end

Problem? undefined method 'date_start' for nil:NilClass. I assume the problem is the first Chain record hasn't been saved, so I added:

Chain.save # in between the two loops

This didn't work either. How can I make this work? Thank you!

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about datetime