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 5 years have passed since last update.

rails 発展その8 form_forとform_tagの使いわけ

Last updated at Posted at 2019-11-11

form_forとform_tagの違い

form_for: 入力フォームにモデルがあれば使用
      投稿、入力フォームなど
paramsに置いてネストされる(2重になる)ため
      params.require(:モデル名).permit(:カラム名)を使用
      

form_tag: モデルがなく特定のアクションに送りたい場合に使用
      検索フォームなど
paramsに置いてネストされないので
      params.permit(:キー名)

form_for

投稿、入力フォームなどに使用
  基本変数を設定し
  入力フォームと送信ボタンを作成するのが基本です。

viewの例
   <%= form_for current_user do |f| %>
   <!--上記でf変数を設定-->   
      <div class="col-lg-6">
        <%= f.text_field :full_name, placeholder: "フルネーム", class: "form-control" %>
      <!--ここで変数を使用して入力フォームを作成 full_nameカラムに入力できるようにする->
      </div>
    <div class="form-group">
      <%= f.submit "送信", class: "btn btn-primary withripple" %>
     <!--送信用のボタンを設定-->
    </div>
  <% end %>
 

form_tag

  検索フォームなどに使用  
  入力内容から特定のアクションを行わせたい時に使用する

require/permitメソッド

特定の情報だけデータを受け取るように設定するメソッド
require: モデルを指定
  permit: カラムを指定

controller
   params.require(:モデル名).permit(:カラム名)
   # form_for用
   params.permit(:キー名)
   # form_tag用  

# 例
 def user_params
  params.require(:user).permit(:name, :age)
 end
 #userモデルにたいし、nameとageカラムだけ許可

mergeメソッド

mergeメソッドは2つのハッシュを統合する時に使うメソッドです。
 別々で入力した内容をまとめたい時など使用

   ha1 = {question: "Who?"}
   ha2 = {group: "camp", name: "abe"}
   ha1.merge(ha2)

# 出力結果
# => {:question=>"Who?", :group=>"camp", :name=>"abe"}

placeholder: ''

フォームの中に、''で囲んだ文字をフォームの値が空の時に薄く表示しておくことができます。

sample.html.erb
    <%= f.text_field :nickname, placeholder: 'ニックネームを入力必須)' %>
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?