根据会话中的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 :user
和has_many :pins
我不明白为什么我会收到这个错误。
答案 0 :(得分:2)
为了澄清,创建错误是因为原始对象(在您的情况下为@pin
)没有填充任何数据(因此它是nil
)。
-
错误强>
许多初学者对此错误感到困惑,但这很简单:
@pin.user
^这会在.user
对象上调用@pin
。 user
方法是从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]
位于列表的顶部。