Rails 4强参数嵌套对象中的嵌套数组

时间:2014-04-26 20:51:00

标签: ruby-on-rails json polygon geojson strong-parameters

This问题部分回答了我的问题。作者使用类似的json结构..

我的问题:如何在嵌套对象中允许嵌套数组?我有一个Contribution模型has_many Features。我正在尝试创建GeoJSON多边形。 coordinates保持空白

这是我发送的JSON

{
  "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"
  }
}

目前我的许可证代码如下:

params.require(:contribution).permit(
  :title,
  :description,
  features_attributes: [
    { geojson: [
        :type,
        { geometry: [
            :type,
            #{ coordinates: [] } # this works for arrays like coordinates: [ 7.62, 51.96 ]
            { coordinates: [[]] }
          ]
        }
      ]
    }
  ]
)

1 个答案:

答案 0 :(得分:9)

我现在就这样解决了。请指正! :)

  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