[英]undefined method for nil:NilClass error in Rails
我在Rails控制器中定义了以下实例变量:
class PagesController < ApplicationController
def about
@story, @story2 = Post.tagged_with("test").all(order: "RANDOM()", limit: 2)
end
end
但是,当我尝试在视图页面中使用变量时,出现以下错误: NoMethodError in Pages#about
: NoMethodError in Pages#about
undefined method user for nil:NilClass
认为没有任何作用。 这是视图中引发错误的部分:
<% if @story.user.photo_file_name.present? %>
<%= image_tag @story.user.photo.url(:avatar) %>
<% else %>
<%= image_tag('avatar.png', :size => "50x50") %>
<% end %>
我在控制器中看不到变量定义有问题。 是什么导致错误?
谢谢!!
似乎您没有任何帖子,因此@story
为nil
您的实例变量不会被填充,因此您的查询一定不能返回任何内容。 数据库中没有与您要查找的内容匹配的内容,或者请求格式错误。
如果您确定数据库中有匹配的记录,我可以尝试使用它作为替代方法以查看是否有帮助:
@story, @story2 = Post.tagged_with("test").order("RANDOM()").limit(4)
正如其他人已经告诉过您的那样,您代码中的某些内容将获得nil值,而实际上不应该。 使用撬来调试代码,
binding.pry
在开始PagesController#about
并开始播放
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.