未定义的方法'用户'对于nil:nilClass

时间:2014-05-27 04:27:04

标签: ruby-on-rails ruby ruby-on-rails-4

根据会话中的One Month Rails课程:Pins Users and Associations我必须在运行rails console后执行以下操作:

Pin.connection #This establishes a connection to the database (And spits out a LOT of unnecessary data)

Pin.inspect #shows all of the parameters for a Pin 
CONTROL + D #closes the Console 

pin = Pin.first #make sure Pin.first is UPPERCASE
pin.user

但是当我写pin.user时,我收到错误NoMethodError: undefined method 'user' for nil:NilClass

我添加了belongs_to :userhas_many :pins

我不明白为什么我会收到这个错误。

我的github是https://github.com/frankzk/pinteresting

3 个答案:

答案 0 :(得分:2)

为了澄清,创建错误是因为原始对象(在您的情况下为@pin)没有填充任何数据(因此它是nil)。

-

错误

许多初学者对此错误感到困惑,但这很简单:

@pin.user 

^这会在.user对象上调用@pinuser方法是从rails关联(belongs_to :user)创建的,旨在为您提供关联数据。

您遇到的问题是您正在对未填充的对象(它是.user类的一部分)调用'nil',从而阻止.user方法实际运行。

-

<强>修正

要解决此问题,您应该这样做:

#app/controllers/pins_controller.rb
Class PinsController < ActieRecord::Base
    def show
        @pin = Pin.find params[:id] #-> or Pin.first
    end
end

#app/views/pins/show.html.erb
<%= @pin.user %>

如果在此之后出现错误,通常意味着您要么数据不一致(数据库中没有数据),要么系统的某些其他部分不连贯。

答案 1 :(得分:0)

请确保引脚表的列名为user_id。或者检查第一个Pin中是否存在数据库中的记录。

答案 2 :(得分:0)

如果你像我一样,你的所有代码都是正确的,Mattan只是把一小段代码放在错误的地方。

class PinsController < ApplicationController

  before_action :authenticate_user!, except: [:index, :show]

  before_action :set_pin, only: [:show, :edit, :update, :destroy]

  before_action :correct_user, only: [:edit, :update, :destroy]

确保before_action :authenticate_user!, except: [:index, :show]位于列表的顶部

编辑:其实我看到你正在上课的早期部分;我会留下这个答案,因为在试图找出授权部分时,我被引导到了这个问题。