To understand the Strong Parameters mechanism in Rails 4, first take a look at Parameters in Rails3.
When creating or updating an Active Record object in Rails3, there will be a Mass Assignment security issue. Therefore, a whitelist is required in the Model to declare which attributes can be updated by parameter data.
Rails 3
# kings_controller.rbdef create #{ name: ‘David', sex:male, age: 31} @king = King.new(params[:king]) if @king.save redirect_to @king else render 'new' endend# king.rbclass King attr_accessible :nameend
Rails 4
Rails 4 introduces the Strong Parameters mechanism. The Model is no longer responsible for white list maintenance, and the responsibility for filtering illegal attributes is pushed to the Controller.
# kings_controller.rbdef create # new parameter { name: ‘David' } @king = King.new(king_params) if @king.save redirect_to @king else render 'new' endendprivatedef king_params # old parameter { name: ‘David', sex:male, age: 31} # new parameter { name: ‘David' } params[:king].permit(:name)end# king.rbclass Kingend
What is Strong Parameters?
To put it bluntly, Strong Parameter is a layer of whitelist filtering.
The data passed through the View layer is converted into an ActionController: Parameters object.
Filter the old ActionController: Parameters object and generate a new ActionController: Parameters object.
* Only whitelist attributes are retained.
* The instance variable @ permitted is set to true.
Pass the filtered ActionController: Parameters object to the model to create or update the corresponding ActiveRecord object.
Can the model be passed over to the overlord?
ActionController: @ permitted of Parameters object not filtered by Strong Parameter is false (true after filtering ). If the Model is passed over, the error ActiveModel: ForbiddenAttributesError is returned.