Playbook
Search…
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:
1
def user_params
2
params.require(:user)
3
end
4
​
5
# This method is called from the view, we call it url_options instead of url_params because it doesn't contain a params object.
6
def url_options
7
user_params.to_h.merge(utm_params.to_h)
8
end
Copied!
  • 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.
1
def post_user
2
SomeUserServiceWorker.perform_async(user_params.to_h)
3
end
4
​
5
def user_params
6
params.require(:user).permit!
7
end
Copied!
We put 2 spaces before private:
1
​
2
​
3
private
Copied!

​

Last modified 2yr ago
Copy link
Contents