开发者

Rails variable loads first time and then is nil!

开发者 https://www.devze.com 2023-01-11 21:43 出处:网络
I am receiving the following error: ActionView::TemplateError (You have a nil object when you didn\'t expect it!

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 contr开发者_如何学JAVAoller 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!


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
0

精彩评论

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