Rails, strong parameters, and complex data structures

Viewed 234

Good aftern, SO folks

I am strong parameterizing a Rails 3 application that we plan to upgrade to Rails 4. Some of the controllers use the params object to hold not just nested hashes, but hashes within arrays within hashes within arrays etc. Changing the nature of the data structure would be too intense, we want to ideally have it return the same data structure, but strong parameterized

Here's an example as JSON:

"my_example" => {
  "options" =>
   [{"id" => "1"
     "name" => "claire"
     "keywords" => 
       ["foo", "bar"]
     },
    {"id" => "2",
      "name" => "marie",
      "keywords => 
        ["baz"]
    }],
    "wut" => "I know, right?"
}

But for added fun, the keywords array can contain any string. Which I've read about and which is tricky and supported in other versions of rails but whatever.

Are there any general rules of thumb about making complex data structures with the strong_parameters gem? I know that Rails 4 and 5 handle this better, but I'm curious.

1 Answers

Nested parameters are not really that challenging.

params.require(:my_example)
      .permit(:wutz, options: [:id, :name, keywords: []])

This expects that options is an array of resources where the keys :id, :name, and :keywords are to be whitelisted.

:wutz, :id, :name can be any permitted scalar type. keywords: [] permits an array of any scalar type (any string, integer, date, etc). I don't really get why you're fretting here.

The issue is mainly with nested hashes with extremely dynamic contents. In that case which is not quite covered the Rails strong parameters you can use .permit! and unleash the full tools of Ruby hash slicing and dicing which are quite formidable.

The gem pretty much backports the api of ActionController::Parameters in later versions of Rails pretty closely so I would not expect any major hickups when upgrading.

https://github.com/rails/strong_parameters#nested-parameters

Related