我正在使用設計進行用戶驗證。並有三個模型,文章,評論和用戶。只允許評論的所有者刪除他們的評論
我只有登錄用戶才能添加評論到文章的能力。而且我也有在評論表中添加用戶標識的評論。但是,我正在努力實現限制評論作者刪除他們自己的評論的功能。
我有什麼:
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,以便我們知道要銷燬哪條評論? –
是的,所以我們知道是否讓用戶銷燬註釋 –