[RUBY] About require when setting strong parameters

Operating environment Ruby 2.6.5 Rails 6.0.3.2

It took me a while to understand the difference between when a strong parameter is required and when it is not required, so I posted it.

If require is required

ruby:new.html.erb


<%= form_with model:@hoge, local: true do |f| %>
  <%= f.text_area :fuga %>
<%= f.submit "Post" %>

hoges_controller.rb


def create
  @hoge = Hoge.create(hoge_params)
end

private
def hoge_params
  params.require(:hoge).permit(:fuga)
end

In the above case, require (: hoge) is required for the strong parameter. This is because fuga is included in the hoge of params that is sent when you click Post. Actually, if you check params in the create action using binding.pry, it will be as follows. Suppose you have entered "example" in fuga.

{"authenticity_token" => "+ wXNK4Z3C0wrq4AfslPS5zl / 2LSUE6BvV + 23hQpkHryrsVzPb0siDIkarIsNYLK2R502fuXlqQ ==", "hoge"> = {"fuga" => "Example"}, "commit" => " "," action "=>" create "}

If require is not required

ruby:new.html.erb


<%= form_with url:hoge_path, local: true do |f| %>
  <%= f.text_area :fuga %>
<%= f.submit "Post" %>

hoges_controller.rb


def create
  @hoge = Hoge.create(hoge_params)
end

private
def hoge_params
  params.permit(:fuga)
end

In the above case, the strong parameter does not need to be required. This is because hoge does not exist in the params sent when you click post, it contains fuga directly. Actually, if you check params in the create action using binding.pry, it will be as follows. Suppose you have entered "example" in fuga.

{"authenticity_token" => "+ wXNK4Z3C0wrq4AfslPS5zl / 2LSUE6BvV + 23hQpkHryrsVzPb0siDIkarIsNYLK2R502fuXlqQ ==", "fuga" => "Example", "commit" => "Post", "controller" => " "create"}

As mentioned above, you can see that hoge does not exist unlike before.

Summary

In other words, it turns out that the strong parameter require is used to pull out the input (fuga in this case) in params from an element (hoge in this case).

Roughly speaking, require is required when model is specified in form_with. If you do not specify it, you can say that require is not necessary.

Recommended Posts

About require when setting strong parameters
About rails strong parameters
[Strong parameters]
Summary of strong parameters
[Ruby] Strong parameters [require] [permit] [merge] How to use Role
Setting maintenance when installing Eclipse
[rails] What are Strong Parameters?
Enable strong parameters in devise