[Ruby] About rails strong parameters

1 minute read

What are strong parameters?

Are the parameters sent from wed to the server the intended data? After verification, it is a mechanism to acquire and register. __view file __

sample.html


<%= form_for @sample do |f| %>
 <div class="name_from">
   <%= f.text_field :name, placeholder: "Enter user name" %>
 </div>
 
<div class="addles_from">
   <%= f.text_field :addles, placeholder: "Enter address" %>
 </div>
 
<div class="mail_from">
   <%= f.text_field :mail, placeholder: "Enter email" %>
 </div>

 <div class="actions">
  <%= f.submit %>
</div>
<% end %>

controller

sample_controller.rb


def index
end

def create
  Sample.create(sample_params)
end

private

def sample_params
  params.permit(:name, :mail)
end

Processing order The request parameters entered on the screen are passed to the action of the controller as a hash type. I will omit it considerably, but this time, I will proceed assuming that the process passes to the create action. When processing passes to the create action __, the __sample_params action __ is called within the action. In __sample_params action __, make sure that the request parameters get only the intended values, __params.permit method __ is used. This __permit method __ is very important and if you use this method, It takes only the requested request parameters, creates a new hash type, and returns the value to the create action. This time, it is easy to understand, and only __:name, :mail are used as the arguments of permit method __. Request parameters are __{name: “aaa”, addles: “Tokyo”, mail: “[email protected]”} It is sent to the server, and the request parameter value is sent to the create action of the sample controller. Three parameters were sent, but the only value I want is :name,:mail, so I sent it. addles: “Tokyo” will be played. __ In this way, in order to prevent unintended values being sent, falsifying data etc., and registering illegal data, Strong parameters are required. Roughly speaking, strong parameters are such a mechanism that only obtains the intended parameters. By the way, the parameter returned by __permit method __ has a value like this. When sending (request parameter __{name: “aaa”, addles: “Tokyo”, mail: “[email protected]”}

Return value after permit method __ is processed __{name: “aaa”, mail: “[email protected]”} In this way, unnecessary parameters are removed and a new hash is returned.

Tags: ,

Updated: