Brief discussion on strong parameters mechanism _ruby special topic in Rails 4

Source: Internet
Author: User

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.

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.