1

I'm developing a Rails application, and in order to see the app with some demo content, I created a rake task to populate the database with some dummy data. The relevant code is here:

def make_comments
  Post.all(:limit => 100).each do |post|
    6.times do
      author  = Author.find_by_id(rand(100) + 1)
      content = Faker::Lorem::sentence(5)
      author.comments.create!(
        :post_id  => post,
        :content  => content
      )
    end
  end
end

When I run this code in the Rails console, I have no problems, but when run through rake (method is called from the task "db:populate"), I get the error:

rake aborted!
You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.each

What might be the problem? I'm running Ruby 1.9.2, Rake 0.8.7, and Rails 3.0.3, if that helps. My impression is that there is some problem retrieving the Posts from the database, but as I said, I have no issues when run through "rails console."

Any help on this issue would be very much appreciated! I can give more details about my setup if needed, but the issue seems to be linked with Rake/Rails.

Thanks!

Edit: I still don't know what was going wrong here, but I managed to get it working by iterating through some of the authors and then having them comment on random posts. This solution works better for mocking up data as well, I think.

3
  • Have you considered using the builtin db:seed functionality that rails provides? Commented Dec 12, 2010 at 4:39
  • Can you post your rake task as well? My hunch is, your Rake task is not depending on <code>environment</code>. Your task should look like this: task :populate => :environment do SomeClass.make_comments end Commented Dec 12, 2010 at 4:47
  • @violet I did have the proper environment settings, but apparently @Beerlington's suggestion of the new limit syntax did fix the issue. Commented Dec 12, 2010 at 13:57

2 Answers 2

1

What happens if you use the Rails 3 query syntax instead?:

Post.limit(100).each ...
Sign up to request clarification or add additional context in comments.

2 Comments

This fixed the issue! Thanks so much, I didn't even know that Rails 3 had this new syntax!
That's just the tip of the iceberg. Checkout the Rails Guides guides.rubyonrails.org/active_record_querying.html
1
Post.find(:all, :limit => 100).each do |post|

1 Comment

I still got the same error - thinking the problem may just be a bug with Rake.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.