Reference: active_record_validations.html#format
Reference: activemodel
Reference:
There are two main use cases. The first to make sure that no extra parameters are accidentally passed into create/update operations. This is to address any "mass assignment" vulnerability.
The second case is that RESTful controllers often have parameters not contained in the URL and hence not checked by the routing logic. To validate those, we first construct a white-list:
nparams = params.permit( :my_param_a, :my_param_b, ...)
Note these are somewhat validated as being a basic type (see the reference above), but they aren't fully validated.
Here is an example model which includes ActiveModel::Model
Adding checking to a controller
Each controller action is responsible for handling parameter white-list and required presence.
The idea is to define a nested class within the controller that is responsible for parameter checking. To avoid having a class per action, one ensures that named parameters are used consistently across all actions. For example, params[:email] should always be an e-mail address. Don't use names like :arg1 across multiple actions where it is an integer in one and an e-mail address in another.
The nested class then supplies validators for each parameter name. The validates should not check for presence as that was already handled by the action.
After the white-list and requires, one instantiates the CheckParams class using the cleaned-up parameters. One then checks to see if the instantiation is valid. If not, one produces a response with status 400 (bad request).
No comments:
Post a Comment