0

我有一个包含文章和评论的应用程序(教程)。一篇文章有​​_许多评论。评论属于文章。我在删除文章评论时遇到问题。以下是有问题的文件:

app/views/comments/_comment.html.erb

<%= div_for comment do %>
<h3>
  <%= comment.name %> &lt;<%= comment.email %>&gt; said:
<span class='actions'>
  <%= link_to 'Delete', [@article, comment], confirm: 'Are you sure?', method: :delete %>
</span>
</h3>
<%= comment.body %>
<% end %>

评论控制器

  before_filter :load_article

  def create
    @comment = @article.comments.new(params[:comment])
    if @comment.save
      redirect_to @article, :notice => 'Thanks for your comment'
    else
      redirect_to @article, :alert => 'Unable to add comment'
    end
  end

  def destroy
    @comment = @article.comments.find(params[:id])
    @comment.destroy
    redirect_to @article, :notice => 'Comment deleted'
  end

  private
    def load_article
      @article = Article.find(params[:article_id])
    end

路线.rb

resources :articles do
  resources :comments
end

问题是当我在地址localhost:3000/articles/1并尝试删除评论时。我没有被重定向到文章显示操作,而是在地址localhost:3000/articles/1/comments/3处收到此错误:

Unknown action
The action 'show' could not be found for CommentsController

非常感谢任何帮助,谢谢,迈克

4

1 回答 1

1

这里有两个基本选项,因为大多数浏览器中的链接只能发送 GET 请求。

第一个选项是将 java-script 默认文件包含到页面中

<%= javascript_include_tag :defaults %> #this mocks a delete action by modifying the request automatically

第二个也是更可取的是使用 button_to 代替。首先,一个地方的链接和一个做某事的按钮在逻辑上是分开的。删除绝对是一个动作。此外,蜘蛛不会跟随按钮,因此不会意外调用任何内容。

<%= button_to 'delete', @comment, :method => :delete %> 

========= 完整编辑 ======= 如果您担心链接和按钮看起来不一样,一个简单的解决方案是让我们jquery/jquery_ui为所有链接和按钮设置样式相同的。

于 2012-08-06T12:48:45.833 回答