Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 Nested Array in Nested Object in Strong Parameters

This question answered my question partly. The author uses a similar json structure..

My Question: How to permit nested arrays in a nested object? I have a Contribution model with has_many Features. I am trying to create GeoJSON polygons. The coordinates stays empty

This is the JSON I am sending

{
  "contribution": {
    "features_attributes": [
      {
        "geojson": {
          "type": "Feature",
          "properties": {},
          "geometry": {
            "type": "Polygon",
            "coordinates": [
              [
                [
                  7.263336181640625,
                  52.07190953840937
                ],
                [
                  7.263336181640625,
                  52.135173926548894
                ],
                [
                  7.404785156249999,
                  52.135173926548894
                ],
                [
                  7.404785156249999,
                  52.07190953840937
                ],
                [
                  7.263336181640625,
                  52.07190953840937
                ]
              ]
            ]
          }
        }
      }
    ],
    "title": "324",
    "description": "23"
  }
}

Currently my permit code looks like this:

params.require(:contribution).permit(
  :title,
  :description,
  features_attributes: [
    { geojson: [
        :type,
        { geometry: [
            :type,
            #{ coordinates: [] } # this works for arrays like coordinates: [ 7.62, 51.96 ]
            { coordinates: [[]] }
          ]
        }
      ]
    }
  ]
)
like image 421
ubergesundheit Avatar asked Apr 26 '14 20:04

ubergesundheit


1 Answers

I solved it now like this. Please correct me! :)

  params.require(:contribution).permit(
    :title,
    :description,
    features_attributes: [
      {
        geojson: [
          :type,
          { geometry: [
              :type,
              { coordinates: [] },
              coordinates: []
            ]
          }
        ]
      }
    ]
  ).tap do |whitelisted|
    whitelisted['features_attributes'].try(:each_index) do |i|
      whitelisted['features_attributes'][i]['geojson']['geometry']['coordinates'] = params['contribution']['features_attributes'][i]['geojson']['geometry']['coordinates']
    end
  end
like image 191
ubergesundheit Avatar answered Nov 08 '22 22:11

ubergesundheit