Ruby on Rails——一个完整的例子(八)

本节是关于这个blog项目的article相关的例子的最后一节,让我们一起来学习一下如何删除一个article。

要实现删除的动作,我们需要在controller中添加destroy方法,在destroy方法中,我们需要知道要删除的对象,所以至少需要把article的id作为参数传递过来。

def destroy

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

  @article.destroy

 

  redirect_to articles_path

end

 对应controller里的create方法,我们新建了一个view(new.html.erb);对应controller里的update方法,我们也新建了一个view(edit.html.erb);而针对现在的destroy,我们不需要新建一个view与之相对应,因为删除不需要独立的页面与之对应,我们删除之后只需返回list页面就可以了。(对应我们之前完成的index.html.erb)

我们需要在这个view中加入destroy的操作,对其修改如下:

<h1>Listing Articles</h1>

<%= link_to 'New article', new_article_path %>

<table>

  <tr>

    <th>Title</th>

    <th>Text</th>

    <th colspan="3"></th>

  </tr>

 

  <% @articles.each do |article| %>

    <tr>

      <td><%= article.title %></td>

      <td><%= article.text %></td>

      <td><%= link_to 'Show', article_path(article) %></td>

      <td><%= link_to 'Edit', edit_article_path(article) %></td>

      <td><%= link_to 'Destroy', article_path(article),

              method: :delete,

              data: { confirm: 'Are you sure?' } %></td>

    </tr>

  <% end %>

</table>

我们发现在article的表单中,destroy的部分额多了两个参数,一个是method,一个是data。method指定的delete告诉Rails我们要执行的命令,data部分则弹出一个确认对话框,方便用户确认是否执行该删除操作。如果用户确认了,那么Rails会执行delete命令。

启动rails server之后,我们看到的效果如下:

点击Destroy之后,

 

然后我们点击确定,

 

这样,删除记录的操作我们就完成了。 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章