Rails 变量第一次加载,然后为零!

发布于 2024-09-15 02:06:49 字数 735 浏览 8 评论 0原文

我收到以下错误:

ActionView::TemplateError (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.include?) on line #24 of app/views/index/index.html.erb:
21: <% @achievements.each do |achievement| %>
22:     <%= achievement.name %>
23:     <%= achievement.level %>
24:     by <%= achievement.user.username %><br/>
25: <% end %>

奇怪的是,第一次加载索引页时没有任何问题。当我刷新时,我收到上面的错误。

控制器看起来像这样:

class IndexController < ApplicationController
    def index
        @achievements = Achievement.find(:all)
    end
end

与缓存有关吗?或者它使用了太多内存?如果是这样,我可以用其他方式加载用户名吗?我很困惑!

I am receiving the following error:

ActionView::TemplateError (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.include?) on line #24 of app/views/index/index.html.erb:
21: <% @achievements.each do |achievement| %>
22:     <%= achievement.name %>
23:     <%= achievement.level %>
24:     by <%= achievement.user.username %><br/>
25: <% end %>

The strange thing is that when the index page is loaded the first time then there is no problem whatsoever. When I refresh, I get the error above.

The controller looks like this:

class IndexController < ApplicationController
    def index
        @achievements = Achievement.find(:all)
    end
end

Is it something to do with the caching? Or is it using too much memory? If so, can I load the username in another way perhaps? I'm confused!

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

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

发布评论

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

评论(1

失而复得 2024-09-22 02:06:49

尝试通过在查找中添加“:include => :user”来急切加载用户:

class IndexController < ApplicationController
    def index
        @achievements = Achievement.find(:all, :include => :user)
    end
end

Try eager loading the users by adding ":include => :user" in your find:

class IndexController < ApplicationController
    def index
        @achievements = Achievement.find(:all, :include => :user)
    end
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文