在 Rails 中迭代数组时出现问题

发布于 2024-10-07 08:28:18 字数 953 浏览 1 评论 0原文

我正在开发一个 Rails 应用程序,为了查看该应用程序的一些演示内容,我创建了一个 rake 任务来使用一些虚拟数据填充数据库。相关代码在这里:

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

当我在 Rails 控制台中运行此代码时,没有任何问题,但是当通过 rake 运行时(从任务“db:populate”调用方法),我收到错误:

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

可能是什么问题?我正在运行 Ruby 1.9.2、Rake 0.8.7 和 Rails 3.0.3(如果有帮助的话)。我的印象是,从数据库检索帖子时存在一些问题,但正如我所说,通过“rails 控制台”运行时没有任何问题。

任何有关这个问题的帮助将非常感激!如果需要,我可以提供有关我的设置的更多详细信息,但问题似乎与 Rake/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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

岁吢 2024-10-14 08:28:18

如果您改用 Rails 3 查询语法会发生什么?:

Post.limit(100).each ...

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

Post.limit(100).each ...
探春 2024-10-14 08:28:18
Post.find(:all, :limit => 100).each do |post|
Post.find(:all, :limit => 100).each do |post|
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文