Introduction to Strong Parameters mechanism in Rails 4

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.