Params

Params management

From Rails 4 onwards, Strong Params have been introduced in Rails. These are a way of forcing developers to whitelist the params they expect before using mass assignment, eg. if the params look like this: <ActionController::Parameters {"first_name"=>"John", "last_name": "Doe"} permitted: true>then we could do User.update(params)because as we can see these params have been whitelisted. However in SeraphinWeb we don't use mass assignment, because we almost exclusively use our own form of whitelisting:

  • When we pass the params to a forms, these only assign the expected attributes to a model (instead of assigning whatever was sent to the form)

  • In presenters we extract the needed attributes from the params in the initialize method

Params are an ActionController::Parametersobject, which the forms can handle nicely because they access the attributes they need by key. However there are certain use cases where we need params to be a hash. To transform them with to_h we need them to be permitted first.

  • Merging multiple param categories

  • Sending the params to an external service

Keeping these exceptions in mind, this is the convention for using params in SeraphinWeb:

  • A method named something_params is always an ActionController::Parametersobject, for which by default we don't permit the attributes because we assume they will be further down the line:

def user_params
    params.require(:user)
end

# This method is called from the view, we call it url_options instead of url_params because it doesn't contain a params object.
def url_options
    user_params.to_h.merge(utm_params.to_h)
end
  • If we need them to be permitted (because we need the params to be a hash), we permit them inside this method but they still remain an object. We only transform them to a hash when we need the hash.

def post_user
    SomeUserServiceWorker.perform_async(user_params.to_h)
end

def user_params
    params.require(:user).permit!
end

We put 2 spaces before private:



private

Last updated