What is `params.require(:person).permit(:name, :age)` doing in Rails 4?

前端 未结 2 1967
孤街浪徒
孤街浪徒 2020-12-07 07:41

All the examples of strong parameters in Rails 4 docs use

params.require(:person).permit(:name, :age)

Could someone please deconstruct and

相关标签:
2条回答
  • 2020-12-07 08:12

    To be more precise, when you create for eg. doing .new(...), there must be :person hash indicated by require and the person hash will only accept :name and :age indicated by permit.

    Example:

    .new(person: { name: "Bhojendra", age: 32 }) // okay
    .new(person: { name: "Rauniyar" }) // okay
    .new(person: { name: "Bhojendra", other: 'asdf' }) // not okay, other not permitted
    .new(person: { full_name: "Bhojendra Rauniyar" }) // not okay, full_name not permitted
    .new(detail: { name: "Bhojendra", age: 32 }) // not okay, must be person
    
    0 讨论(0)
  • 2020-12-07 08:21

    The params in a controller looks like a Hash, but it's actually an instance of ActionController::Parameters, which provides several methods such as require and permit.

    The require method ensures that a specific parameter is present, and if it's not provided, the require method throws an error. It returns an instance of ActionController::Parameters for the key passed into require.

    The permit method returns a copy of the parameters object, returning only the permitted keys and values. When creating a new ActiveRecord model, only the permitted attributes are passed into the model.

    It looks a lot like the whitelisting that was formerly included in ActiveRecord models, but it makes more sense for it to be in the controller.

    0 讨论(0)
提交回复
热议问题