LoginSignup
0
4

More than 3 years have passed since last update.

form_tagとform_forの違い

Posted at

form_tagの使い方

1.ルーティングのパスとhttpメソッドを直接定義する。


<%= form_tag('/products/search', method: :get) do %>

2.新規投稿の場合、コントローラのnewアクションにモデルクラスのインスタンス変数を定義しなくてもよい。

tweets_controller.rb
class TweetsController < ApplicationController
   def new
   end
end

3.新規登録の保存におけるストロングパラメータは,permit(:カラム名)という書き方をする。

tweets_controller.rb

private
 def tweet_params
   params.permit(:name, :text)
 end

form_forの使い方

1.ルーティングのパスとhttpメソッドを直接書き込む必要はなく、モデルクラスのインスタンス変数を引数に定義する。form_forの場合、モデルクラスのインスタンス変数の中身に値が、代入されていない場合はcreateアクションが作動し、代入されている場合はupdateアクションが作動するように自動化されているからである。

2.新規投稿の場合、コントローラのnewアクションにモデルクラスのインスタンス変数を定義する必要がある。引数に渡すためのインスタンス変数が必要となるからである。

tweets_controller.rb
class TweetsController < ApplicationController
   def new
      @tweet = Tweet.new
   end
end

3.ルーティングのネストの回数によって、引数に渡すインスタンス変数の個数が変化する。

例えば、ルーティングを一回ネストさせた場合は、

routes.rb
resources :tweets do
    resources :comments, only: [:create]
  end

インスタンス変数の個数は、ネストの親のルーティングのtweetsとネストの子のcommentsの2つが必要となる。よって、form_forの引数は、@tweetsと@commentsとなる。

comments_controller.rb
class CommentsController < ApplicationController  
  def new
    @tweet = Tweet.find(params[:id])
    @comment = Comment.new
  end
end

<%= form_for ( [@tweet, @comment] ) do |f| %>

3.新規登録の保存におけるストロングパラメータは、require(:モデル名)permit(:カラム名)という書き方をする。

tweets_controller.rb

private
 def tweet_params
   params.require(:tweet).permit(:name, :text)
 end

form_forを使用し場合、一回モデルというキーを取り出して、その中にあるカラムというモデルのバリューかつparamsのキーであるカラムを取り出すという二重構造(二重ハッシュ)になっているからである。

form_tagの場合は、パスを直接指定しているため、モデルクラスを経由しないので、このような構造にはならない。

<参考資料>
https://guides.rubyonrails.org/v5.1/form_helpers.html

0
4
1

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
4