Reputation:
I've tried to debug this error, but cannot figure out what is wrong with my code.
I am using the devise gem for users and current_user
is a devise method
I am trying to add a before action to my documents controller to prevent editing, updating and destroying a document when not the user who has uploaded it.
This is the error: undefined method 'documents' for nil:NilClass
The error is reffering to the private method authorized_user
This is my controller code:
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
I'm not sure why i'm getting the undefined method for the documents
Upvotes: 0
Views: 55
Reputation: 19039
The problem is that your filters are ran in the order you declared them.
Let's look at them:
before_action :authorized_user, only: [:edit, :update, :destroy]
before_filter :authenticate_user!, except: [:index, :show]
The first filter checks for document permissions, the second one checks that the user is authenticated. Do you see the issue?
You need to swap the them:
before_action :authorized_user, only: [:edit, :update, :destroy]
before_filter :authenticate_user!, except: [:index, :show]
This will guarantee that authorized_user
is not called if the user is logged out – and voila!
Upvotes: 1