In this writing, I will explain the benefits and dangers of mass assignment and use params.permit
to allow specific params.
What is mass assignment?
The mass assignment passes a :key => value
params hash to a model's create()
or new()
method to create an instance.
A benefit of using a mass assignment
The mass assignment can simplify creating an instance of a model with multiple attributes.
AnimalTrainer.create(
name: params[:name],
email: params[:email],
favorite_species: params[:favorite_species],
admin: params[:admin]
)
Instead of typing every single attribute:params[:attribute]
, using mass assignment with one params argument will look like as simple as
params = {
name: "Emma",
email: "iluvpanda@gmail.com",
favorite_species: "Pink Panda",
admin: true
}
AnimalTrainer.create(params)
A danger of using mass assignment
Mass assignment in its nature has a vulnerability where :key => value
params hash will be accepted as is. For an example, I can send a params hash such as :admin => true
or :email => "illegalemail@gmail.com"
.
Strong params
To prevent "dangerous params hash", you can create a function with using params.permit
to allow specific params.
class AnimalTrainersController < ApplicationController
# POST /animal_trainers
def create
trainer = AnimalTrainer.create(animal_trainer_params)
render json: trainer, status: :created
end
# other controller actions here
private
# all methods below here are private
def animal_trainer_params
params.permit(:name, :email, :species)
end
end
The animal_trainer_params
function now filters "unassigned" :key => value
params hash to the prevent mass assignment vulnerability.
My understanding of strong params is like an attendance sheet in a classroom where you cannot be sitting in the classroom and you do not have an access to the class materials if your name is not on the attendance sheet.
An example from my code:
If you would like to know more details about strong params and mass assignment, please refer to Rails Guide Mass Assignment.
Resources
Mass Assignment Vulnerability:
https://en.wikipedia.org/wiki/Mass_assignment_vulnerability
Strong params:
https://guides.rubyonrails.org/action_controller_overview.html#strong-parameters
Top comments (0)