我跟着One Month Rails一起關注,並且我陷入了引腳用戶和關聯視頻。我只是不知道我的代碼有什麼問題,任何幫助將不勝感激。NoMethodError在調用關聯的has_many模型時設計current_user
當我試圖訪問一個引腳,我不是的用戶,而不是警報和重定向來了,我得到:
NoMethodError in PinsController#edit
undefined method `pins' for nil:NilClass
錯誤消息說,什麼是錯的在這條線:
def correct_user
@pin = current_user.pins.find_by(id: params[:id])
redirect_to pins_path, notice: "Not authorized to edit this pin" if @pin.nil?
end
我試過重新啓動整個事情,但我碰到了同樣的錯誤。
這裏是我的pins_controller代碼:
class PinsController < ApplicationController
before_action :set_pin, only: [:show, :edit, :update, :destroy]
before_action :correct_user, only: [:edit, :update, :destroy]
before_action :authenticate_user!, except: [:index, :show]
def index
@pins = Pin.all
end
def show
end
def new
@pin = current_user.pins.build
end
def edit
end
def create
@pin = current_user.pins.build(pin_params)
if @pin.save
redirect_to @pin, notice: 'Pin was successfully created.'
else
render action: 'new'
end
end
def update
if @pin.update(pin_params)
redirect_to @pin, notice: 'Pin was successfully updated.'
else
render action: 'edit'
end
end
def destroy
@pin.destroy
redirect_to pins_url
end
private
# Use callbacks to share common setup or constraints between actions.
def set_pin
@pin = Pin.find(params[:id])
end
def correct_user
@pin = current_user.pins.find_by(id: params[:id])
redirect_to pins_path, notice: "Not authorized to edit this pin" if @pin.nil?
end
# Never trust parameters from the scary internet, only allow the white list through.
def pin_params
params.require(:pin).permit(:description)
end
end
這裏是我的user.rb型號代碼:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :pins
end
這裏是我的pin.rb型號代碼:
class Pin < ActiveRecord::Base
belongs_to :user
end
而且這裏是github回購: https://github.com/ModernMeat/pinteresting
你如何定義'current_user',你在哪裏實例化它?錯誤代碼表明'current_user'不存在(爲零)。 – JTG