注释函数:未定义的方法"注释"为 nil:NilClass



我想为我的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中的@postnil,因为它第一次设置在#destroy中。此外,您的Comment模型当前与User模型没有关系,@post.comment.user.id不起作用,因为#user也将未定义。

若要更正此问题,请在CommentUser仅在正确的用户调用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 

最新更新