我有一个用户和文章模型,用户可以拥有许多模型,并将删除功能限制为用户或管理员。然而,当我试图破坏文章时,我收到以下错误:
未定义的方法`user'代表nil:NilClass
并指向我的文章控制器中的这个私有函数:
def require_same_user
if current_user != @article.user and !current_user.admin?
flash[:danger] = "You can only edit or delete your own articles"
redirect_to root_path
end
end
这是我的整个控制器文件:
class ArticlesController < ApplicationController
before_action :set_article, only: [:edit, :update, :show]
before_action :require_user, except: [:index, :show]
before_action :require_same_user, only: [:edit, :update, :destroy]
def index
@articles = Article.paginate(page: params[:page], per_page: 5)
end
def show
end
def new
@article = Article.new
end
def edit
end
def update
@article.update(article_params)
if @article.save
flash[:success] = "Article successfully updated!"
redirect_to article_path(@article)
else
flash[:danger] = "Sorry, try again..."
render :edit
end
end
def create
@article = Article.new(article_params)
@article.user = current_user
if @article.save
flash[:success] = "New article created"
redirect_to articles_path
else
flash[:danger] = "Sorry, invalid values"
render :new
end
end
def destroy
@article = Article.find(params[:id])
@article.destroy
flash[:success] = "Article deleted"
redirect_to articles_path
end
private
def article_params
params.require(:article).permit(:name, :title, :description)
end
def set_article
@article = Article.find(params[:id])
end
def require_same_user
if current_user != @article.user and !current_user.admin?
flash[:danger] = "You can only edit or delete your own articles"
redirect_to root_path
end
end
端
文章和用户存在于db中,这可能是什么?提前谢谢
答案 0 :(得分:2)
您使用set_article
功能设置文章,但在require_same_user
功能的情况下,它不知道{{1}的值是什么1}};所以在这种情况下,值为nil,因为它不在范围内,也不是之前创建的实例变量。
@article
一种方法可能是将def require_same_user
# Here there's no @article, so it's evaluated as nil,
# and nil doesn't have a method user.
if current_user != @article.user ...
...
设置为在set_article
执行之前执行。
require_same_user
您还可以将代码分成较小的部分,以便在需要时再次使用:
before_action :set_article, only: %i[edit update show require_same_user]
答案 1 :(得分:1)
确保在destroy
操作之前运行before_action :set_article, only: [:edit, :update, :show, :destroy]
。
在您的控制器中:
{"name":"asfd","username":"awsf","email":"kean","age":"21","gender":"Male","submit":"Submit"},
{"name":"asdf","username":"asfd","email":"asdf@asdf","age":"21","gender":"Male","submit":"Submit"},
{"name":"null","username":"null","email":"null@gmail.com","age":"21","gender":"Male","submit":"Submit"},
{"name":"null","username":"null","email":"null@gmail.com","age":"21","gender":"Male","submit":"Submit"},