我正在使用设计进行用户验证。并有三个模型,文章,评论和用户。只允许评论的所有者删除他们的评论
我只有登录用户才能添加评论到文章的能力。而且我也有在评论表中添加用户标识的评论。但是,我正在努力实现限制评论作者删除他们自己的评论的功能。
我有什么:
comment.rb
class Comment < ApplicationRecord
belongs_to :user
belongs_to :article
end
user.rb
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
has_many :comments
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
article.rb
class Article < ApplicationRecord
has_many :comments, dependent: :destroy
end
Comments_controller
class CommentsController < ApplicationController
before_action :authenticate_user!
before_action :find_comment, only: [:create, :destroy]
before_action :comment_auth, only: [:edit, :update, :destroy]
#Some items removed for brevity
def destroy
@comment = @article.comments.find(params[:id]).destroy
redirect_to article_path(@article)
end
private
def comment_params
params.require(:comment).permit(:name, :body, :user_id)
end
def find_comment
@article = Article.find(params[:article_id])
end
def comment_auth
if @comment.user_id != current_user.id
flash[:notice] = 'You are not owner of this comment.'
redirect_to(root_path)
end
end
我还添加上的评论表的外键:试图删除我创建了一个用户评论,并登录时
class AddForeignKeys < ActiveRecord::Migration[5.0]
def change
add_foreign_key :comments, :users
end
end
然后,我得到:
NoMethodError in CommentsController#destroy
undefined method `user_id' for nil:NilClass
我错过了什么?
谢谢@Deepak这似乎确实奏效。我的comment_auth对评论的编辑和更新也有限制,我将如何用您的方法替换它。 是的,指出关于限制链接破坏只有登录用户。 –
太棒了。这也是有效的。谢谢。 因此,在销毁评论之前,我现在是否找到相关的评论ID和文章ID,以便我们知道要销毁哪条评论? –
是的,所以我们知道是否让用户销毁注释 –