Betax Betax - 1 year ago 41
TypeScript Question

Rails has_many input from Angular2 front end won't save

I'm building an Angular 2 front-end app that's getting data from a Rails 5 API. It's a kind of network inventory app.

I've got a Asset-form in Angular2 and there's an multi-select input for the ip_addresses of the asset.

I'm unable to get Rails to accept this data in the back-end.

The asset object:


Here's my 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, formData, { headers })
.map((response: Response) => response.json());}

This is what im getting in the Rails server console:

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",

Unpermitted parameter: ip_address_ids

I've permitted the param of 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 => [])

The strange thing is that if I use the Advanced REST Client in Chrome It's successful.

Here's an image of the REST Client

The result in the Rails server console:

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

I think that the problem is that Angular sends the IDs as a string and the REST Client sends the IDs as an Array of strings.

Any idea on how to fix this?

Answer Source

Your ip_address_ids params is being passed as string, rather than array, why not use formData = JSON.stringify({asset: asset}) instead of custom processing?

If the case is that you want to pass it as an actual string you should not permit it with => [], only :ip_address_ids would be enough.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download