LoginSignup
0
1

More than 5 years have passed since last update.

初心者がRailsガイドを1から100まで読んでみる Railsをはじめよう編その13 データの削除

Posted at

5.13.記事を削除する

CRUDの最後の機能を実装しましょう。
Create→済
Read→済
Update→済
Delete→イマココ

スクリーンショット 2018-09-16 23.04.57.png

おあつらえ向きなアクションがありますね。
そう、destroyアクションです。

それじゃあいつもの
①コントローラにアクションを追加
②ビューを作成
しましょう。

article_controller.rb
class ArticlesController < ApplicationController

    def index
        @articles = Article.all
    end

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

    def new
        @article = Article.new
    end

    def create
        @article = Article.new(article_params)

        if @article.save
            redirect_to @article
        else
            render 'new'
        end
    end

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

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

        if @article.update(article_params)
            redirect_to @article
        else
            render 'edit'
        end
    end

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

        redirect_to articles_path
    end

    private
        def article_params
            params.require(:article).permit(:title, :text)
        end
end

destroyアクションを追加しました。

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

        redirect_to articles_path
    end

削除したい記事をfindしてdestroyしてますね。
そのあとarticles_pathにリダイレクトしている。
ルーティングから確認するとarticles_pathはindexアクションへのパスだ。
消した後一覧に戻る動きだね。

ビューだけど、削除ページなんて特にいらないので、一覧に削除するリンクを貼ればOK

index.html.erb

<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>
    <td><%= link_to 'Destroy', article_path(article),
                    method: :delete, data: { confirm: 'Are you sure?' } %></td>

他のリンクとちょっと違うけど、こう書くことで確認ダイアログが出てその後削除してくれる。

スクリーンショット 2018-10-01 2.49.23.png

僕の黒歴史を全部消してやったぞ!
スクリーンショット 2018-10-01 2.50.06.png

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1