Andrew
Andrew

Reputation: 810

How to use params.fetch strong parameters

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.

Upvotes: 39

Views: 28799

Answers (3)

Felipe H.
Felipe H.

Reputation: 21

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).

Upvotes: 2

Fernando Oléa
Fernando Oléa

Reputation: 281

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

params.fetch(:kitten, {}).permit(:name, :age)

Upvotes: 28

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230551

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)

Upvotes: 46

Related Questions