控制器中的Destroy方法问题 - ROR

时间:2014-07-08 02:11:38

标签: ruby-on-rails ruby-on-rails-4.1

当我尝试从维基中删除某篇文章时,会发出错误"无法找到带有ID的文章..."

破坏方法:

def destroy
    @article=Article.find(params[:id])
    @article.destroy

    flash.notice="Article '#{@article.title}' was deleted"

    redirect_to article_path
end

show view(show.html.erb):

<h1><%= @article.title %></h1>
<p><%= @article.body %></p>
<%= link_to "<<Back to Articles List", articles_path %>
<%= link_to "Delete", article_path(@article), method: :delete, data: {confirm: "Really delete this article?"} %>

5 个答案:

答案 0 :(得分:0)

When I try to delete an article from a wiki, it throw an error "can't find article with id..."

错误消息说明了一切。您正在尝试删除不存在的对象。它可能曾经存在但它不再存在。

示例:假设错误消息显示"can't find article with id=5"

打开您的rails console,然后搜索ID = 5的文章:

Article.find(5)

它会告诉你它找不到文章:

ActiveRecord::RecordNotFound: Couldn't find Child with id=5

您的代码看起来不错。只是你正在尝试删除不存在的东西。

返回console,找到现有文章。尝试删除该文章,你会发现你的代码工作正常

答案 1 :(得分:0)

问题出在这里:

  
      
  1. 您的数据库没有您要删除的记录
  2.   
  3. 您没有通过正确的paramd[:id]
  4.   

如果没有看到你的params日志,我只能引用你的link_to方法,以便了解发生了什么。如果您想要更明智的回复,您需要向我们展示您收到的params哈希

-

<强>修正

为什么不尝试直接调用对象(因此link_to将能够尽可能有机地引用路径):

<%= link_to "Delete", @article, method: :delete, data: {confirm: "Really delete this article?"} %>

当然,这是考虑到您的@article记录已正确编译等

-

您将遇到的另一个问题是,在中销毁了您的记录后,您正在调用redirect_to article_path

当然,您需要重定向到articles_path - 文章的index(根据资源丰富的系统)?

答案 2 :(得分:0)

您的控制器代码是正确的......然后还要检查两种方法......

def index
    @article = Article.all

    respond_to do |format|
      format.html # call index.html.erb
      format.json { render json: @article }
    end
  end

def destroy
    @article = Article.find(params[:id])
    @article.destroy

    respond_to do |format|
      format.html { redirect_to articles_url }
      format.json { head :no_content }
    end
  end

检入您的查看 article / index.html.erb 文件

<table>
  <tr>
    <th>Article Title</th>
    <th>Description</th>
    <th></th>
    <th></th>
    <th></th> 
  </tr>
<% @article.each do |article| %>
  <tr>
    <td><%= article.title %></td>
    <td><%= article.body %></td>
    <td><%= link_to 'Show', article %></td>
    <td><%= link_to 'Edit', edit_article_path(article) %></td>
    <td><%= link_to 'Destroy', article, method: :delete, data: { confirm: 'Are you sure?' } %></td> 
  </tr>
<% end %>
</table>

<br />

<%= link_to 'New Article', new_article_path %>
</div>

如果你收到错误,那么仍然是 添加到您的destroy方法

@article = Article.find(params[:id]) rescue ""

答案 3 :(得分:0)

我遇到了同样的问题。您需要做的就是将“redirect_to article_path”更改为“redirect_to articles_path”。它们是两条不同的路径。

祝你好运。

答案 4 :(得分:0)

禁止在articles_controller.rb中插入代码?

Private IQueryable<Insurer> GetInsurers(DateTime UserSelectedDate)
{
    return db.Insurers(dt=> dt.StartDate >= UserSelectedDate && dt.StopDate <= UserSelectedDate)
}