Reputation: 65
I want the user who created post and admin to delete but it's throwing me an 'undefined error'. I want to know why it's throwing me an undefined method error.
Here's my code from the controller:
Before actions:
before_action :set_recipe, only: [:edit, :update, :show, :like]
before_action :require_user, except: [:show, :index, :like]
before_action :require_user_like, only: [:like]
before_action :require_same_user, only: [:edit, :update]
before_action :admin_or_authorship, only: :destroy
Destroy method:
def destroy
Recipe.find(params[:id]).destroy
flash[:danger] = "Deleted"
redirect_to stories_path
end
private
def recipe_params
params.require(:recipe).permit(:name, :summary, :description)
end
def set_recipe
@recipe = Recipe.find(params[:id])
end
def require_same_user
if current_user != @recipe.user and !current_user.admin?
flash[:danger] = "You can only edit your own recipes"
redirect_to stories_path
end
end
def require_user_like
if !logged_in?
flash[:danger] = "log in to like!"
redirect_to :back
end
end
def admin_or_authorship
redirect_to stories_path unless administrator? || authorship?
end
def administrator?
current_user.admin?
end
def authorship?
@recipe.user == current_user
end
Upvotes: 1
Views: 228
Reputation: 9747
The problem is that in your before_filter admin_or_authorship
, which is further calling authorship?
, is saying @recipe.user ...
. Here @recipe
is not defined so is nil
by default.
You need to call before_filter set_recipe
for destroy
too:
before_action :set_recipe, only: [:edit, :update, :show, :like, :destroy]
Your action will become:
def destroy
@recipe.destroy
flash[:danger] = "Deleted"
redirect_to stories_path
end
Upvotes: 1