Rails创建端点一次接受多个对象的方法

时间:2015-02-16 14:15:42

标签: ruby-on-rails ruby-on-rails-4 strong-parameters

我需要创建一个一次接受多个对象的端点。下面的示例请求(json正文):

{
    "obd_bluetooth_events" : [
        {
            "car_id": 1,
            "obd_plugin_id": "1",
            "kind": "CONNECT",
            "date": 1422369149
        },
        {
            "car_id": 1,
            "obd_plugin_id": "1",
            "kind": "DISCONNECT",
            "date": 1422369149
        },
        {
            "car_id": 1,
            "obd_plugin_id": "1",
            "kind": "CONNECT",
            "date": 1422369149
        }
    ]
}

因此,为了能够传递数组来创建方法:@obd_bluetooth_event.create(obd_bluetooth_events_params)

我需要像这样定义obd_bluetooth_events_params方法:

def obd_bluetooth_events_params
  params.permit(
    obd_bluetooth_events: [
      :car_id, 
      :obd_plugin_id, 
      :kind, 
      :date
    ]
  )[:obd_bluetooth_events]
end

打电话给我后:

Unpermitted parameters: obd_bluetooth_event
=> [{"car_id"=>1, "obd_plugin_id"=>"1", "kind"=>"CONNECT", "date"=>1422369149},
 {"car_id"=>1, "obd_plugin_id"=>"1", "kind"=>"DISCONNECT", "date"=>1422369149},
 {"car_id"=>1, "obd_plugin_id"=>"1", "kind"=>"CONNECT", "date"=>1422369149}]

我想知道是否有更多的方法来允许一系列物体?

1 个答案:

答案 0 :(得分:0)

def obd_params params.require(:myparams).permit(:myarray => []) end

我可以正常使用数组。 希望这会有所帮助;)