2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Rails] 情報編集画面に遷移した際、編集前の情報が全てフォームに入力された状態にする

Last updated at Posted at 2020-12-30

投稿した本の詳細ページから編集ページに遷移した際、
すでにフォームに現在の投稿情報が入力されている状態を作る。

Books_controller.rb
class BooksController < ApplicationController

  def edit
    @book = Book.find(params[:id])
  end
end
edit.html.erb
<div class="books-sell-main">
  <h2 class="books-sell-title">本の情報を入力</h2>
  <%= form_with model: @book, local: true do |f| %>
    <%= f.file_field :image, id:"book-image" %>
    <%= f.text_area :title, class:"books-text", id:"book-name" %>
  <% end %>
</div>

<%= form_with model: @book, local: true do |f| %>の@bookには
items#editで取得したレコードの情報が格納されており、それをブロック変数 f にも
保持させています。
これのおかげでf.text_fieldと書くだけで、@bookに格納されている情報を呼び出し
ビューに反映することができます。

パスの指定が必要ないのは
form_withの機能で、
引数として渡されたモデルクラスのインスタンスが中身の入ったインスタンスの場合、updateアクションへ処理を振り分けてくれているからです。

反対に、引数として渡されたモデルクラスのインスタンスが中身の入っていないインスタンスの場合は、createアクションへ処理を振り分けてくれます。

今回の@bookは中身の入ったインスタンスのため、updateアクションへ振り分けられます。


データベースに保存しない場合のform_withの書き方

<%= form_with url: "パス" do |form| %>
  # フォーム内容
<% end %>

データベースに保存する場合のform_withの書き方

<%= form_with model: モデルクラスのインスタンス do |form| %>
  # フォーム内容
<% end %>
2
3
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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?