Ruby on rails 调用关联时设计当前用户的命名错误有多个模型
我跟随了一个月的Rails,我被Pins用户和协会的视频卡住了。我只是不知道我的代码出了什么问题,任何帮助都将不胜感激 当我尝试访问我不是用户的pin时,我得到的不是警报和重定向,而是:Ruby on rails 调用关联时设计当前用户的命名错误有多个模型,ruby-on-rails,ruby,Ruby On Rails,Ruby,我跟随了一个月的Rails,我被Pins用户和协会的视频卡住了。我只是不知道我的代码出了什么问题,任何帮助都将不胜感激 当我尝试访问我不是用户的pin时,我得到的不是警报和重定向,而是: NoMethodError in PinsController#edit undefined method `pins' for nil:NilClass 错误消息表示此行有问题: def correct_user @pin = current_user.pins.fin
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
我试着重新启动整个程序,但遇到了同样的错误
这是我的PIN_控制器代码:
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
class PinsController
以下是我的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
class Pin < ActiveRecord::Base
belongs_to :user
end
class用户
以下是我的pin.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
class Pin < ActiveRecord::Base
belongs_to :user
end
class Pin
以下是github回购协议:
仔细查看错误消息:
“for nil:NilClass”
。这告诉您当前用户是nil
——当用户未登录时确实是这样
如果要确保用户已登录以访问Pins
控制器,可以在控制器中使用before\u action
:
class PinsController < ApplicationController
before_action :authenticate_user!
class PinsController
(authenticate\u user!
是designe声明的方法)。我建议您更改的顺序,然后再像这样进行筛选
class PinsController
因为您应该首先使用designe对用户进行身份验证,然后才检查它是否是正确的用户。您如何定义当前用户
,您在哪里实例化它?错误代码表明当前用户不存在(为零)。这很有效,非常感谢!这似乎是一个非常简单的解决方案,我想我应该试着思考事情发生的顺序,而不是遵循教程。