【问题标题】:Rails variable loads first time and then is nil!Rails 变量第一次加载然后为零!
【发布时间】:2010-08-18 13:56:44
【问题描述】:

我收到以下错误:

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

这与缓存有关吗?还是它使用了太多的内存?如果是这样,我可以用另一种方式加载用户名吗?我很困惑!

【问题讨论】:

  • 在此处显示您的控制器操作
  • 上面添加的控制器操作
  • 尝试通过在你的 find (Achievement.find(:all, :include => :user) 中添加 ":include => :user" 来快速加载用户
  • 嗨,杰夫,这行得通。谢谢。

标签: ruby-on-rails model null actionview


【解决方案1】:

尝试通过在您的查找中添加“:include => :user”来预先加载用户:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-24
    • 1970-01-01
    • 1970-01-01
    • 2017-12-12
    • 2019-10-31
    • 2021-12-21
    相关资源
    最近更新 更多