LoginSignup
0

More than 5 years have passed since last update.

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

Last updated at Posted at 2018-09-30

5.11.記事を更新する

次は記事の更新機能をつけましょう。
Create→済
Read→済
Update→イマココ
Delete

まずはルーティングの確認
スクリーンショット 2018-09-16 23.04.57.png

edit!
それっぽいのがあるじゃないか!

それじゃあ
①アクションの追加
②ビューの作成
をしよう

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

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

editアクションをコントローラに追加したよ。

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

もともとある記事を更新するわけだからインスタンス変数にはfindして見つかった記事を格納しているね。

edit.html.erb
<h1>Edit article</h1>

<%= form_with(model: @article, local: true) do |form| %>
  <% if @article.errors.any? %>
  <div id="error_explanation">
    <h2><%= pluralize(@article.errors.count, "error") %> prohibited
      this article from being saved:</h2>
    <ul>
    <% @article.errors.full_messages.each do |msg| %>
      <li><%= msg %></li>
    <% end %>
    </ul>
  </div>
  <% end %>
  <p>
    <%= form.label :title %><br>
    <%= form.text_field :title %>
  </p>

  <p>
    <%= form.label :text %><br>
    <%= form.text_area :text %>
  </p>

  <p>
    <%= form.submit %>
  </p>
<% end %>

<%= link_to 'Back', articles_path %>

edit.html.erbを作成したよ。
基本的にはnew.html.erbとおんなじだね。

大きく違うのはこの部分

<%= form_with(model: @article, local: true) do |form| %>

form_withってビューヘルパーの使い方は以前出てきたけど、今回は引数にmodel: @articleを指定している。

「articleオブジェクトをこのメソッドに渡すと、編集済みの記事を送信するときに使うURLが魔法のように自動作成されます。 Railsはこのオプションによって、PATCHというHTTPメソッドをでこのフォームを送信しようとしていることを認識します。PATCHメソッドは、RESTプロトコルに基いてリソースを更新する場合に使います。」

なんかよくわからないけど、form_withの引数にモデルを渡すと、PATCHでupdateアクションに送信されるんだって。 これもRailsちゃんの察しの良さというわけらしい。

editは更新内容を記載するところで、その内容はupdateアクションに送られる。
じゃあ次はupdateアクションを実装して、更新内容をモデルに保存しよう。

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

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

updateアクションを追加したよ。
createアクションととっても似ている。
ちがうのはfindしてみつけた記事をupdateしているところだね。

最後にeditページのリンクを貼りまくろう。

index.html.erb
<h1>Listing articles</h1>

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

<table>
  <tr>
    <th>Title</th>
    <th>Text</th>
    <th colspan="2"></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>
  </tr>
<% end %>
</table>

スクリーンショット 2018-09-30 14.39.13.png
Editリンクが追加された。

show.html.erb
<p>
  <strong>Title:</strong>
  <%= @article.title %>
</p>

<p>
  <strong>Text:</strong>
  <%= @article.text %>
</p>

<%= link_to 'Back', articles_path %>
| <%= link_to 'Edit', edit_article_path(@article) %>

スクリーンショット 2018-09-30 14.40.50.png

更新すると…
スクリーンショット 2018-09-30 14.41.30.png

保存される!
スクリーンショット 2018-09-30 14.41.37.png

参考

Railsガイド
https://railsguides.jp/getting_started.html

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