37

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.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
Andy
  • 720
  • 1
  • 7
  • 13

3 Answers3

44

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)
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
  • 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 `permit` – Andy Aug 15 '17 at 15:56
  • 4
    `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] || {}`. – max Aug 15 '17 at 16:27
  • 8
    @max `params.fetch(:kitten, {})` is plain Ruby, not ActiveSupport : ) – m. simon borg Aug 15 '17 at 17:43
26

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

params.fetch(:kitten, {}).permit(:name, :age)
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
Fernando Oléa
  • 261
  • 3
  • 3
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).

Azametzin
  • 5,223
  • 12
  • 28
  • 46
Felipe H.
  • 21
  • 4