5.11.記事を更新する
次は記事の更新機能をつけましょう。
Create→済
Read→済
Update→イマココ
Delete
edit!
それっぽいのがあるじゃないか!
それじゃあ
①アクションの追加
②ビューの作成
をしよう
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して見つかった記事を格納しているね。
<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アクションを実装して、更新内容をモデルに保存しよう。
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ページのリンクを貼りまくろう。
<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>
<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) %>