1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Rails入門】form_withは魔法の絨毯!

Posted at

はじめに

こんにちは!Railsでユーザー登録や投稿フォームを作るとき、<form>タグの複雑さに頭を抱えたことはありませんか? actionのURLはこれで合ってる? methodpost? あの呪文みたいなauthenticity_tokenって何だっけ…?

そんな面倒な作業からあなたを解放してくれる、Railsの魔法の道具が**form_withヘルパー**です!

form_withがない世界(手書きの茨の道)

もしform_withがなかったら、私たちはユーザー登録フォームを以下のように全部手で書く必要があります。

<form action="/users" method="post">
  <input type="hidden" name="authenticity_token" value="(毎回変わる秘密の文字列)">

  <label for="user_name">名前</label>
  <input type="text" id="user_name" name="user[name]">

  <label for="user_email">メールアドレス</label>
  <input type="email" id="user_email" name="user[email]">

  <input type="submit" value="登録する">
</form>

これは大変です。URLやセキュリティ対策、各inputタグのname属性など、一つでも間違えると正しく動作しません。

form_withの魔法(Railsという名の絨毯に乗って)

form_withを使えば、上記の複雑なフォームが信じられないほどシンプルになります。

▼ RailsのView (Slim記法) で書いた場合

= form_with model: @user do |f|
  .field
    = f.label :name
    = f.text_field :name

  .field
    = f.label :email
    = f.email_field :email

  .actions
    = f.submit

たったこれだけで、先ほどの手書きHTMLとほぼ同じものが、安全かつ正確に生成されます。


なぜこんなに短くなるの? form_withの自動化機能

form_withは、渡されたモデルオブジェクト(@user)の状態を見て、たくさんのことを自動で判断してくれます。

  1. 適切なURLとHTTPメソッドを自動設定 🤖

    • @user新規 (User.new) なら 👉 登録用のフォーム (action="/users", method="post") を生成。

    • @user既存 (User.find(1)) なら 👉 更新用のフォーム (action="/users/1", method="patch") を生成。

  2. セキュリティ対策を自動化 🛡️

    • CSRF(クロスサイトリクエストフォージェリ)攻撃を防ぐためのauthenticity_tokenを自動で埋め込んでくれます。
  3. 入力項目とモデルを自動で紐付け 🔗

    • f.text_field :nameと書くだけで、モデルのname属性と関連付けられたname="user[name]"という属性を自動で生成します。

おわりに

form_withの 素晴らしさが少しでも伝われば嬉しいです☺️

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?