[Ruby] [Strong parameters]

1 minute read

What are strong parameters

Strong parameters.png

I will explain what are the strong parameters that appear when defining actions in the controller.

There is a description of create(tweet_params) in the execution content of the create action, but this argument tweet_params is defined in the private method.

private method

Private is a method that cannot be called from outside the class. There are two advantages to using private methods:

Isolate methods that are troubled when called from outside of ###1.class Since some of the methods cause an error when called from outside the class, it is possible to prevent errors in advance by isolating them.

2. Make your code more readable

Readability as code increases by clearly separating private and non-private parts

In this private method The method tweet_params is defined, and the contents of the process are as follows.

Strong 2.png

Take the tweet model as an argument of require, :name :image :text is taken as an argument of permit.

This means that the data sent from the form is restricted to only parameters with the key specified by permit:name:image:text or less.

The mechanism that receives only the parameter with the specified key is called strong parameter.

By specifying strong parameters, you can prevent parameters other than those specified from being sent and prevent unintended data updates.

For example, if you send a parameter that updates another person’s login password, you can arbitrarily change another person’s password, You need to use strong parameters to prevent this.

Looking at the code again

Strong parameter.png

Since the create method specifies tweet_params as an argument, new data is created and saved via the tweet_params method. Therefore, in this case, the new tweet always has only the strong parameter specified in the argument of permit.