我希望创建帖子和管理员的用户可以删除但是它会给我一个“未定义的错误”。我想知道为什么它会给我一个未定义的方法错误。
这是来自控制器的代码:
行动前:
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
破坏方法:
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
答案 0 :(得分:1)
问题在于,您的before_filter admin_or_authorship
正在进一步调用authorship?
,正在说@recipe.user ...
。此处@recipe
未定义,默认情况下为nil
。
您还需要为set_recipe
调用before_filter destroy
:
before_action :set_recipe, only: [:edit, :update, :show, :like, :destroy]
您的行动将成为:
def destroy
@recipe.destroy
flash[:danger] = "Deleted"
redirect_to stories_path
end