Params

Params classes are mostly used by controllers to format the params they have received in the request they're handling. These custom params can then be used by commands to validate frontend data before processing them.

In our MVC+ framework, we have developed a custom class called ApplicationParams. This is the parent of all our params classes. This parent class includes ActiveModel::Model and ActiveModel::Serialization. It allow us to use validations and errors on our params.

Those classes are used for 2 reasons:

  • To permit params: verifying that every params can be present

  • To validate params: validating the format, the presence of said params

Example

Here is an example of a params class:

class NewUserParams < ApplicationParams

  permitted :email, :first_name, :last_name

  validates :email, 
            format: { with: URI::MailTo::EMAIL_REGEXP }
  validate :not_already_persisted

  def not_already_persisted
    return if User.find_by(email: @email).nil?
    errors.add(:email, 'already_taken')
  end
end

How to use it?

Let's say we are in the create action of the UserController. Before asking our User model class to create a new user, we want to verify the params received from the frontend.

Basically, in the controller we will create a new instance of our UserParams class. Note that we use the jsonapi_parse(params) method that we have declared in our ApplicationController class.

new_user_params = ::NewUserParams.new(jsonapi_parse(params))

After that, you can use this object to check if your params are valid by simply doing:

new_user_params.invalid? #Returns true or false

If they are valid, you are good to go to the next step of the processing! If not, your frontend should send you valid params before doing any kind of processing.

Permissions

We can see that the permitted method (line 3) allows three attributes: email, first_name and last_name.

If you instantiate a NewUserParams with another param, it won't be taken into account as this param wasn't permitted.

Validations

Validations are used to validate the presence, the format or anything else about params. If we take a look again at our NewUserParams class, we can see at the line 5 that it validates the presence of the email attribute and it also validates that the email has the appropriate format. If any of these two validations fails, the new_user_paramsinstance will be marked as invalid.

Validations can also be processed via a custom method, as you can see on line 7:

validate :not_already_persisted

This will call the not_already_persisted method, which will directly return if the user doesn't exist yet, or will add an error in the other case. You can now see how you can manually add errors yourself:

errors.add(:email, 'already_taken')

This results in invalidating the new_user_params instance by adding an error on the email attribute.

Last updated