Ruby学习——Rails官方文档踩坑(二)

坑3:The action 'show' could not be found for CommentsController

描述:在article的show页面删除comment的时候,删除完成需要返回到之前的show页面,但是此时页面会报错CommentsController中没有show方法,报错截图如下:


原因:CommentsController中没有show方法

解决方法一:在CommentsController添加show方法

整个CommentsController代码如下:

class CommentsController < ApplicationController
  def create
    @article = Article.find(params[:article_id])
    @comment = @article.comments.create(comment_params)
    redirect_to article_path(@article)
  end

  def destroy
    @article = Article.find(params[:article_id])
    @comment = @article.comments.find(params[:id])
    @comment.destroy
    redirect_to article_path(@article)
  end

  def show #需要添加的show方法
    @article = Article.find(params[:article_id])
    @comment = @article.comments.find(params[:id])
    @comment.destroy
    redirect_to article_path(@article)
  end

  private
    def comment_params
      params.require(:comment).permit(:commenter, :body)
    end
end

解决方法二:把_comment.html.erb文件中删除链接link_to 改成button_to

修改前_comment.html.erb代码如下:

<p>
  <strong>Commenter:</strong>
  <%= comment.commenter %>
</p>

<p>
  <strong>Comment:</strong>
  <%= comment.body %>
</p>

<p>
  <%= link_to 'Destroy Comment', [comment.article, comment],
              method: :delete,
              data: { confirm: 'Are you sure?' } %>
</p>

修改后_comment.html.erb代码如下:

<p>
  <strong>Commenter:</strong>
  <%= comment.commenter %>
</p>

<p>
  <strong>Comment:</strong>
  <%= comment.body %>
</p>

<p>
  <%= button_to 'Destroy Comment', [comment.article, comment],
              method: :delete,
              data: { confirm: 'Are you sure?' } %>
</p>

参考博客

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容