无法删除Rails中的任何注释模型

时间:2016-01-09 20:34:35

标签: ruby-on-rails

删除其他内容工作正常。它看起来与我的帖子控制器(它正在工作)相同,但不会删除评论。

resources :comments, only: [:create, :destroy]

_comment partial

<% if current_user?(comment.user) %>
  <%= link_to "[Delete]", comment, method: :delete,
                                   data: { confirm: "You sure?" } %>
<% end %>

评论控制器

  before_action :logged_in_user, only: [:create, :destroy]
  before_action :correct_user,   only: :destroy

  def destroy
    @comment.destroy
    # @comment = @post.comments.find(params[:id]).destroy
    flash[:success] = "Comment deleted"    
    redirect_to @post
  end

  private

    def correct_user
      @comment = current_user.comments.find_by(id: params[:id])
      redirect_to request.referrer || root_url
    end

1 个答案:

答案 0 :(得分:5)

您的before_action :correct_user@comment.delete操作中调用destroy之前重定向请求。

def correct_user
  @comment = current_user.comments.find_by(id: params[:id])
  # This line below is the problem.
  redirect_to request.referrer || root_url
end

您可以改进的其他一些事项:

@comment = current_user.comments.find_by(id: params[:id])

find_by在这里是多余的。如果您使用id来获取记录,请使用find

@comment = current_user.comments.find(params[:id])

find还有提出ActiveRecord::RecordNotFound错误的好处,该错误转换为生产中未找到404的回复。

如果您想重定向,则无需执行此操作:

  redirect_to request.referrer || root_url

您可以执行redirect_to :back,这是在Rails中。

最后,我会将您的correct_user重命名为set_comment。我不认为correct_user表达了代码的意图,即加载评论。你应该最终得到这个:

before_action :set_comment, only: :destroy

def destroy
  @comment.destroy
  redirect_to :back
end

def set_comment
  @comment = current_user.comments.find(params[:id])
end