来自Angular2前端的Rails has_many输入不会保存

时间:2017-02-06 13:20:16

标签: ruby-on-rails json api angular typescript

我正在构建一个Angular 2前端应用程序,该应用程序从Rails 5 API获取数据。它是一种网络库存应用。

我在Angular2中有一个资产表单,并且资产的ip_addresses有一个多选输入。

我无法让Rails在后端接受此数据。

资产对象:

{"name":"SERVER_A","serial":"XOR-354","location_id":1,"asset_type_id":1,"model_id":3,"ip_address_ids":[5304,5305]}

这是我的asset.service.ts:

createAsset(asset: Asset){

let formData = new FormData();

for(var key in asset){
  if(key == "ip_address_ids") {
    for (var i = 0; i < asset[key].length; i++) {
        formData.append("asset["+key+"][]", JSON.stringify(asset[key][i]));
        console.log("asset["+key+"][]", JSON.stringify(asset[key][i]));
    }

  }
  if(key != "id") {
    formData.append("asset["+key+"]", asset[key]);
  }
}

let headers = new Headers();

let authToken = localStorage.getItem('auth_token');
headers.append('Authorization', authToken);  

return this.http.post(this.assetUrl, formData, { headers })
                .map((response: Response) => response.json());}

这就是我在Rails服务器控制台中的内容:

Started POST "/assets" for ::1 at 2017-02-06 13:58:33 +0100 


Processing by AssetsController#create as HTML   


Parameters: {"asset"=>{"name"=>"SERVER_A", "description"=>"undefined",
"serial"=>"XOR-354", "asset_tag"=>"undefined",
"firmware"=>"undefined", "ssh"=>"undefined", "telnet"=>"undefined",
"http"=>"undefined", "location_id"=>"1", "asset_type_id"=>"1",
"model_id"=>"3", "prtg_id"=>"undefined", "ticket_id"=>"undefined",
"ip_address_ids"=>"5304,5305"}}   

Unpermitted parameter: ip_address_ids

我已经允许ip_address_ids的参数

def asset_params
  params.require(:asset).permit(:name, :description, :serial, :asset_tag, :firmware, :ssh, :telnet, :http, :location_id, :asset_type_id, :model_id, :prtg_id, :ticket_id, :ip_address_ids => [])
end

奇怪的是,如果我在Chrome中使用高级REST客户端它是成功的。

Here's an image of the REST Client

Rails服务器控制台中的结果:

Started POST "/assets" for ::1 at 2017-02-06 14:04:42 +0100

Processing by AssetsController#create as HTML

Parameters: {"asset"=>{"name"=>"Test", "asset_type_id"=>"2", "location_id"=>"33", "model_id"=>"4", "ip_address_ids"=>["5213", "5214"]}}

我认为问题在于Angular将ID作为字符串发送,而REST Client将ID作为字符串数组发送。

有关如何解决这个问题的想法吗?

1 个答案:

答案 0 :(得分:0)

您的ip_address_ids参数是作为字符串而不是数组传递的,为什么不使用formData = JSON.stringify({asset: asset})而不是自定义处理?

如果您希望将其作为实际string传递,则不应允许=> [],只有:ip_address_ids就足够了。