开发者

Problem while iterating through Array in Rails

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.


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

Post.limit(100).each ...


Post.find(:all, :limit => 100).each do |post|
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜