whitelisting deeply nested strong parameters in ra

2020-08-01 11:39发布

问题:

I'm trying to store a serialized Ransack search in a text column. It's deeply nested and I'm struggling coming up with permit call for it. Here's a sample hash:

{
  "c"=>{
    "0"=>{
      "a"=>{
        "0"=>{
          "name"=>"column_1"
        }
      },
      "p"=>"eq",
      "v"=>{
        "0"=>{
          "value"=>"value_1"
        }
      }
    },
    "1"=>{
      "a"=>{
        "0"=>{
          "name"=>"column_2"
          }
      },
      "p"=>"cont",
      "v"=>{
        "0"=>{
          "value"=>"value_2"
        }
      }
    }
  }
}

How would you write a permit for that? This is my best guess for reading the doc but it isn't working.

def course_listing_params
  params.require(:course_listing).permit({ q: { c: [{ a: [:name] }, :p,  { v: [:value] }] } })
end

回答1:

I ended up building another model to store the conditions and using accepts_nested_attributes_for to create the conditions all within the course_listing controller.

I had to add

conditions_attributes: [:id, :attr, :pred, :val, :_destroy]

to my permit call in order to make everything work. The middle three are my own attributes, the :id prevents Rails from adding new conditions with every edit, and the :_destroy is so you can delete conditions.