私はユーザー認証にdeviseを使用しています。 3つのモデル、記事、コメント、ユーザーがあります。コメントのオーナーのみがコメントを削除できるようにしてください
私は、ログインしたユーザーのみが記事にコメントを追加する機能を持っています。また、コメントテーブルにユーザーIDを追加するコメントもあります。しかし、私は自分のコメントを削除するコメント作成者だけを制限する機能を実装するのには苦労しています。私が持っているもの
:
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を見つけたら、削除するコメントを知ることができますか? –
はい、ユーザーにコメントを破棄させるかどうかはわかります –