How to use params.fetch strong parameters
Asked Answered
C

3

38

When using rails g scaffold kittens the strong parameters function, kitten_params is

def kitten_params
  params.fetch(:kitten, {})
end

I am familiar with strong parameters, params.require(:kitten).permit(:name, :age) but I'm not sure how to use the fetch method for this.

Contestant answered 15/8, 2017 at 15:46 Comment(0)
R
45

but I'm not sure how to use the fetch method for this

Simple. You do not use fetch for this. Since you didn't provide any properties when you created the scaffold, rails didn't know what to put into permit section and generated that code, most sensible for this situation. When you add some fields to your kitten form, upgrade kitten_params to the normal strong params "shape".

params.require(:kitten).permit(:name, :age)
Ruthieruthless answered 15/8, 2017 at 15:50 Comment(4)
Ahh thank you, now I see. Since I didn't pass any properties to the scaffolding, it used fetch, whereas if I DID pass properties, it would use require and permitContestant
params.fetch(:kitten, {}) is just an ActiveSupport way accessing a hash key and retrurning a default value if it is not set. In plain ruby it would read params[:kitten] || {}.Notum
@Notum params.fetch(:kitten, {}) is plain Ruby, not ActiveSupport : )Caston
In newer versions of Rails, params.fetch(...) returns ActionController::Parameters so can you can safely chain it with .require(...) as needed.Linesman
A
28

Accordingly to Documentation, you should just add .permit at the end, like:

params.fetch(:kitten, {}).permit(:name, :age)
Amalita answered 21/11, 2018 at 17:27 Comment(0)
R
2

According to documentation, you can't use .require when you don't have an instance of an object.
Then .fetch supplies a default params for your uncreated object (#new and #create actions).

Revitalize answered 1/3, 2020 at 15:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.