简体   繁体   中英

undefined method for nil:NilClass error in Rails

I have the following instance variables defined in a Rails controller:

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

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. Use pry to debug your code,

  1. see http://railscasts.com/episodes/280-pry-with-rails
  2. put binding.pry at beginning of PagesController#about and start playing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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