调用关联的has_many模型时,Devise current_user的NoMethodError

时间:2014-06-22 20:11:49

标签: ruby-on-rails ruby

我跟随One Month Rails,我被困在Pins用户和协会视频中。我无法弄清楚我的代码有什么问题,我们将不胜感激。

当我尝试访问我不是用户的引脚时,我得到了以下警告和重定向:

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

2 个答案:

答案 0 :(得分:2)

我建议你更改before_filter这样的顺序

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]

因为您应首先使用设计对用户进行身份验证,然后才检查用户是否正确。

答案 1 :(得分:0)

更仔细地查看错误消息:"for nil:NilClass"。这告诉您current_usernil - 当用户未登录时确实如此。

如果您想确保用户已登录以访问Pins控制器,您可以在控制器中使用before_action

class PinsController < ApplicationController
  before_action :authenticate_user!

authenticate_user!是设计声明的方法。)