2016-08-19 4 views
0

私はこのエラーをデバッグしようとしましたが、私のコードに何が間違っているのかわかりません。私がいないときにアップロードしたユーザー文書を更新し、破壊し、編集を防ぐために、マイドキュメントコントローラにアクションの前に追加しようとしています、私はユーザーのための工夫の宝石を使用していますが、current_userが工夫方法メソッドエラーRails

ある

それ。

これはエラーです:undefined method 'documents' for nil:NilClass

エラーはプライベートメソッドにauthorized_user

をrefferingされるこれは私のコントローラのコードです:

class DocumentsController < ApplicationController 
before_action :find_document, only: [:show, :edit, :update, :destroy, :upvote, :dislike] 
before_action :authorized_user, only: [:edit, :update, :destroy] 
before_filter :authenticate_user!, except: [:index, :show] 

def index 
    if params[:category].blank? 
     @documents = Document.all.order(:cached_votes_up => :desc) 

     if params[:search] 
     @documents = Document.search(params[:search]).order(:cached_votes_up => :desc) 
     elsif 
     @documents = Document.all.order(:cached_votes_up => :desc) 
     end 

    else 
     @category_id = Category.find_by(name: params[:category]).id 
     @documents = Document.where(category_id: @category_id).order(:cached_votes_up => :desc) 
    end 
end 

def show 
end 

def new 
    @document = current_user.documents.build 
end 

def create 
    @document = current_user.documents.build(documents_params) 

    if @document.save 
     redirect_to @document 
    else 
     render 'new' 
    end 
end 

def edit 
end 

def update 
    if @document.update(documents_params) 
     redirect_to @document 
    else 
     render 'edit' 
    end 
end 

def destroy 
    @document.destroy 
    redirect_to root_path 
end 

private 

def documents_params 
    params.require(:document).permit(:title, :category_id, :search, :pdf) 
end 

def find_document 
    @document = Document.find(params[:id]) 
end 

def authorized_user 
    @document = current_user.documents.find_by(id: params[:id]) 
    redirect_to documents_path, notice: "Not authorized to edit this Document" if @document.nil? 
end 
end 

私は取得していますなぜ私はわからないんだけど定義されていないドキュメントの方法

+1

'current_user' – Ven

+0

' current_user'がない私 –

答えて

2

問題は、フィルタが宣言した順序で実行されることです。

のは、それらを見てみましょう:文書のアクセス権のための

before_action :authorized_user, only: [:edit, :update, :destroy] 
before_filter :authenticate_user!, except: [:index, :show] 

最初のフィルタをチェックし、もう一つは、ユーザーが認証されていることを確認します。あなたはその問題を見ていますか?

あなたはそれらを交換する必要があります。

before_action :authorized_user, only: [:edit, :update, :destroy] 
before_filter :authenticate_user!, except: [:index, :show] 

これは、ユーザーがログアウトした場合authorized_userが呼び出されないことを保証します - と出来上がり!

+0

それは工夫によって作成されたので、私は、ユーザーのために使用宝石ああどのように私はこれを実現していないで工夫が提供するヘルパーメソッドである私たちに示してください。どうもありがとう。私が5分でできるときに私は受け入れるだろう –

関連する問題