0
0

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.

ヘルパーメソッド formのアウトプット

Posted at

概要

本日の学習でform_withの使用に関して、アウトプットさせて頂きます。

ヘルパーメソッドを使用するメリット

1.パスの指定やRubyの埋め込みなどの記述がシンプルになるため
2.セキュリティ上の問題を解消するため

rails5.1以降はform_forとform_tagはform_withに統合されたため、railsドキュメントではform_withの使用が推奨されているため、こちらを深堀していきたいと思います。


<%= form_with url: "/posts", method: :post, local: true do |form| %>
  <%= form.text_field :content %>
  <%= form.submit '投稿する' %>
<% end %>

form_with url: "/posts", method: :post, local: true do |form|の詳細

url: "/posts"

# urlオプション
# フォームの情報を送るリクエストパスを指定
# rails routesの'URI Pattern'に対応する

↑prefix_pathで代替可能

method: :post
# methodオプション 
# フォームの情報を送るHTTPメソッドを指定。初期値はpostなのでpostメソッドを使う場合のみ省略可能
# rails routesの'Verb'と対応する。

↑モデルオプションで代替可能

local: true do
# リモート送信を無効にするかどうかを指定。trueにすると無効になる
# リモート送信とはAjaxでの通信を行うために必要なもの
|form|
# このブロック変数を使ってフォーム部品を作成する

form.text_field :contentの詳細

フォーム部品の箇所。つまりは実際に入力する場所

form.text_field
# フォーム部品の形式を表す。
# 他のヘルパーメソッドに変更することでチェックボックスやラジオボタンなど入力の方式を変更することができる。
 :content
# 入力した値が保存されるカラムを指定

上記以外の記述は基本的にオプションである。意味はrailsドキュメントで調べる

以上です。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?