1
0

form_withについて

Posted at

form_withについてまとめます。

form_withとは

Ruby on Railsで入力フォームを簡単に作成することができるヘルパーメソッドである。

書き方例

html.erb
<%= form_with (model: @post, local: true) do |f| %>
  <div class="field">
    <%= f.label :title, "タイトル" %><br />
    <%= f.text_field :title %>
  </div>

  <div class="field">
    <%= f.label :content, "内容" %><br />
    <%= f.text_area :content %>
  </div>

  <div class="field">
    <%= f.label :image, "画像" %><br />
    <%= f.file_field :image %>
  </div>

  <div class="actions">
    <%= f.submit "保存する", class: :form__btn  %>
  </div>
<% end %>

解説

<%= form_with (model: @post, local: true) do |f| %>

model:モデルのインスタンスを指定する。
つまり、保存したいテーブルのクラスのインスタンスのこと。

posts_controller
def new
  @post = Post.new # 新規投稿
end

コントローラーに定義した@postを指定する。

|f|はフォームビルダーと呼ばれる。
ラベルやテキストフィールドなどのフォームの要素を作るためにそのビルダーオブジェクトを使う。

f.label #ラベル
f.text_field #テキスト入力欄(複数行の内容などの場合)
f.text_field #一行入力欄(名前、タイトルなど一行の場合)
f.submit #送信ボタン

このまとめにより、一つ一つの役割が明確になりました!

1
0
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
1
0