初めてのRuby on Rails ミニQ&Aサイト開発 - edit, update 更新(4)
初めてのRuby on Rails ミニQ&Aサイト開発 - edit, update更新(4)
routes.rb
Rails.application.routes.draw do
resources :questions
end
- resource :questionsは質問し対するRESTfulラウトを自動に生成し、index, show, new, edit, update, create, destroy アクションのルートを含む。
index.html.erb
<h1>Questions</h1>
<table>
<tr>
<th>ID</th>
<th>Title</th>
<th>Name</th>
<th>Content</th>
</tr>
<% @questions.each do |question| %>
<tr>
<td><%= question.id %></td>
<td><%= question.title %></td>
<td><%= question.name %></td>
<td><%= question.content %></td>
<td><%= link_to 'show', question_path(question) %></td>
<td><%= link_to 'edit', edit_question_path(question) %></td>
</tr>
<% end %>
</table>
- index Viewで全ての ( @questions )を表紙する。
- 各質問に対してshowとeditリンクを提供する。edit_question_path(question)は該当する質問の修正Formに移動するリンクを生成する。
questions_controller.rb
class QuestionsController < ApplicationController
# 質問の編集
def edit
@question = Question.find(params[:id])
end
# 質問の更新
def update
@question = Question.find(params[:id])
if @question.update(question_params)
redirect_to @question
else
render 'edit', status: :unprocessable_entity
end
end
private
def question_params
params.require(:question).permit(:title, :name, :content)
end
end
editアクション
- editアクションはユーザーを特定し、質問を更新するためのFormをユーザーに提供する。
- params[:id]を使ってURLで質問のIDを持ってきて、IDの 'Quesion' インスタンスを探し、@question変数に割り当てる。
updateアクション
- updateアクションは、更新された質問データを受けて該当の質問をupdateする。
- @question.update(question_params)で受けたデータを (qestion_params)で質問をupdateする。
- update成功し、質問の詳細Pageにリダイレクトし、失敗したら更新Formを改めてレンダリングする。
edit.html.erb
<h1>Edit</h1>
<%= form_with model: @question do |form| %>
<% if @question.errors.any? %>
<div>
<ul>
<% @question.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div>
<%= form.label :title %>
<%= form.text_field :title %><br><br>
</div>
<div>
<%= form.label :name %>
<%= form.text_field :name %><br><br>
</div>
<div>
<%= form.label :content %>
<%= form.text_area :content %><br><br>
</div>
<div>
<%= form.submit %>
</div>
<% end %>
- form_with更新する質問( @question )に対するFormを生成する。
- Formの内部で form.label, form.text_field, form_text_area を使って各フィールドに対するlabelと入力フィールドを生成する。
- form.submitを使ってForm提出ボタンを生成する。
https://github.com/designAR/rails_board/tree/update_%2304
GitHub - designAR/rails_board
Contribute to designAR/rails_board development by creating an account on GitHub.
github.com