2016-04-25 37 views
1

エラーが未定義になっています。定義されていないメソッド `pins 'がnil:NilClassの場合、誰かがこのエラーを修正する方法を説明できますか?チュートリアルに従って、最近立ち往生しました。Rails Beginners NoMethodError in PinsController#new


pins_controller.rb

class PinsController < ApplicationController 
    before_action :find_pin, only: [:show, :edit, :update, :destroy] 


    def index 
     @pins = Pin.all.order("created_at DESC") 
    end 

    def new 
     @pin = current_user.pins.build 
    end 


    def create 
     @pin = current_user.pins.build(pin_params) 

     if @pin.save 
      redirect_to @pin, notice: "Successfully created new Pin" 
     else 
      render 'new' 
     end 
    end 

    def edit 

    end 

    def update 
     if @pin.update(pin_params) 
      redirect_to @pin, notice: "Pin was Successfully updated!" 
     else 
      render 'edit' 
     end 
    end 


    def destroy 
     @pin.destroy 
     redirect_to root_path 
    end 


    private 

    def pin_params 
     params.require(:pin).permit(:title, :description) 
    end 

    def find_pin 
     @pin = Pin.find(params[:id]) 
    end 
end 

user.rb

class User < ActiveRecord::Base 
    # Include default devise modules. Others available are: 
    # :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 

routes.rbを

Rails.application.routes.draw do 
    devise_for :users 
resources :pins 

root "pins#index" 
end 
+3

あなたのエラーは 'current_user'が' nil'を返すためです。その方法をチェックしてください(おそらくApplicationControllerで) –

+0

@PetrGazarov私はgem deviseを使いました。それはcurrent_userと一緒に来ました。何を探しているのでしょうか? –

+0

どこでエラーが発生しましたか、どの行ですか? – Lymuel

答えて

1

あなたが工夫使用している場合は、ユーザーがログインしていることを保証ピンコントローラ内部の before_action :authenitcate_user! メソッドを追加したい場合があります。

1

あなたがしている場合Deviseの宝飾品を使用すると、ヘルパーメソッドcurrent_userはセッションに現在ログインしているユーザーを返します。

喜ばは、ユーザーがあなたは、ユーザーが(アプリケーション内のすべてのアクションのために)アプリケーションコントローラでbefore_action :authenitcate_user!を追加することにより、ログインしていることを確認することができます/

に記録されていることを確認します。

+0

ありがとう、私はログインしていません –

+0

恐ろしい、私はあなたを助けることができてうれしい。 – Alfie

関連する問題