我想为我的rails应用程序创建一个注释函数。因此,只有current_user
或管理员(我使用active_admin)才能删除他的评论。但是我很难弄清楚这一点,因为我的方法似乎指向nil
.有人可以帮助我吗?
comments_controller.rb
class CommentsController < ApplicationController
before_action :correct_user, only: :destroy
def create
@post =Post.find(params[:post_id])
@comment =@post.comments.create(params[:comment].permit(:name, :body))
redirect_to post_path(@post)
end
def destroy
@post = Post.find(params[:post_id])
@comment= @post.comments.find(params[:id])
@comment.destroy
redirect_to post_path(@post)
end
private
def correct_user
@user= User.find(current_user.id)
redirect_to(root_url) unless current_user.id == @post.comment.user.id
end
end
在我的correct_user方法中,未定义的注释显示出来,所以我已经尝试添加
@post = Post.find(params[:post_id])
@comment= @post.comments.find(params[:id])
并尝试了不同的方法来运行。
评论.rb
class Comment < ApplicationRecord
belongs_to :post
end
Post.rb
class Post < ApplicationRecord
belongs_to :user
has_many :comments, dependent: :destroy
validates :title, presence: true, length: {minimum: 5}
validates :body, presence: true
validates :user, presence: true
validates :user_id, presence: true
has_attached_file :image #, :styles => { :medium => "300x300>", :thumb =>
"100x100>" }
validates_attachment_content_type :image, :content_type => /Aimage/.*Z/
end
用户.rb
class User < ApplicationRecord
has_many :posts
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
PS:我想用一个 before 操作来做到这一点,然后在删除链接周围使用 if 语句。
>#correct_user
中的@post
是nil
,因为它第一次设置在#destroy
中。此外,您的Comment
模型当前与User
模型没有关系,@post.comment.user.id
不起作用,因为#user
也将未定义。
若要更正此问题,请在Comment
和User
仅在正确的用户调用destroy
操作时调用@comment.destroy
之间的关系。
试试这个,
def destroy
@comment.destroy
redirect_to post_path(@post)
end
private
def correct_user
@comment = Comment.find(params[:id])
@post = @comment.try(:post)
redirect_to(root_url) unless current_user.id == @post.try(:user_id)
end
在params[:id]
这里,我们得到了评论的ID。此外,此@comment.try(:post)
和@post.try(:user_id)
仅在具有您的问题中提到的关联时才有效。
Comment Model
belongs_to :post
Post Model
belongs_to :user