简体   繁体   English

Rails中nil:NilClass错误的未定义方法

[英]undefined method for nil:NilClass error in Rails

I have the following instance variables defined in a Rails controller: 我在Rails控制器中定义了以下实例变量:

class PagesController < ApplicationController
  def about
    @story, @story2 = Post.tagged_with("test").all(order: "RANDOM()", limit: 2)
  end
end

However, when I try to use the variable in a view page I get the following error: NoMethodError in Pages#about undefined method user for nil:NilClass 但是,当我尝试在视图页面中使用变量时,出现以下错误: NoMethodError in Pages#aboutNoMethodError in Pages#about undefined method user for nil:NilClass

Nothing in the view seems to work. 认为没有任何作用。 Here's the part of the view throwing the error: 这是视图中引发错误的部分:

 <% if @story.user.photo_file_name.present? %>
      <%= image_tag @story.user.photo.url(:avatar) %>
   <% else %>
      <%= image_tag('avatar.png', :size => "50x50") %>
 <% end %>

I don't see a problem with the variable definition in the controller. 我在控制器中看不到变量定义有问题。 What is causing the error? 是什么导致错误?

Thanks!! 谢谢!!

似乎您没有任何帖子,因此@storynil

Your instance variables aren't being populated, so your query must not be returning anything. 您的实例变量不会被填充,因此您的查询一定不能返回任何内容。 Either there's nothing in the database matching what you're looking for, or the request is malformed. 数据库中没有与您要查找的内容匹配的内容,或者请求格式错误。

If you're certain you have matching records in the DB, I would try this as an alternative to see if it helps: 如果您确定数据库中有匹配的记录,我可以尝试使用它作为替代方法以查看是否有帮助:

@story, @story2 = Post.tagged_with("test").order("RANDOM()").limit(4)

As other people told you already, something in your code gets nil value and it shouldn't. 正如其他人已经告诉过您的那样,您代码中的某些内容将获得nil值,而实际上不应该。 Use pry to debug your code, 使用撬来调试代码,

  1. see http://railscasts.com/episodes/280-pry-with-rails 参见http://railscasts.com/episodes/280-pry-with-rails
  2. put binding.pry at beginning of PagesController#about and start playing binding.pry在开始PagesController#about并开始播放

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM