To figure out the strong parameters mechanism in Rails 4, first we need to look at the parameters in RAILS3
When you create or update an Active Record object in Rails3, there is a Mass assignment security issue. So the Model needs to list a whitelist and declare which attributes can be updated by the parameter data.
Rails 3
# KINGS_CONTROLLER.RB
def create
#{name: ' David ', Sex:male, age:31}
@king = King.new (params[:king])
If @king. Save
redirect_to @king
Else
render ' new '
end
# king.rb
class King
Attr_accessible:name End
Rails 4
Rails 4 introduced the strong Parameters mechanism, the Model is no longer responsible for the white list maintenance, the filtering of the responsibility of illegal attributes to Controller.
# KINGS_CONTROLLER.RB
def create
# new Parameter {name: ' David '}
@king = King.new (king_params)
if @king . Save
redirect_to @king
Else
render ' new ' end,
private
def king_params
# old parameter {name: ' David ', Sex:male, age:31}
# New Parameter {name: ' David '}
params[:king].permit (: Name)
end
# king.rb
class King
What is strong Parameters?
Plainly strong Parameter It is a layer of white list filtration.
The data passed through the View layer is converted to a actioncontroller::P arameters Object
Filter old Actioncontroller::P arameters object, generate a new Actioncontroller::P arameters object.
* Keep Whitelist attribute only
* Instance variable @permitted assigned to True
Pass the filtered Actioncontroller::P arameters object to model, create or update corresponding ActiveRecord object.
Can be hard to model, Overlord the bow?
Actioncontroller without strong Parameter filtering: The @permitted of the:P Arameters object is False (filtered to true). If the hard to Model, will error activemodel::forbiddenattributeserror.