Rails ujs sending formData in array format instead of index based object

195 views Asked by At

I am trying to send data to my rails server using formData and Rails ujs. The Front end js code looks like this :

 Rails.ajax({
      url: "/reset-cart",
      type: "post",
      data: new FormData(this.formTarget),
      success: function(data) { console.log('success') },
      error: function(data) { console.log('error') }
    })


`Object.fromEntries(new FormData(this.formTarget))` returns 
{
  cart[cart_items_attributes][0][product_id]: "210"
  cart[cart_items_attributes][0][quantity]: "4"
  cart[cart_items_attributes][1][product_id]: "12"
  cart[cart_items_attributes][1][quantity]: "4"
}

In my rails controller I receive data formated this way :

#<ActionController::Parameters {"cart"=>{"cart_items_attributes"=>{"0"=>{"product_id"=>"210", "quantity"=>"4"}, "1"=>{"product_id"=>"12", "quantity"=>"4"}}}, "controller"=>"carts", "action"=>"reset"} permitted: false>

I'd like the data to look more like :

{
  "cart"=> {
    "cart_items_attributes"=> [
      {
        "product_id"=>"210", 
        "quantity"=>"4"
      },{
        "product_id"=>"12",
        "quantity"=>"4"
     }
   ]
 }
}

where cart_items_attributes is a array of hash. Is there a way to achieve that by changing the way I send data in the Rails.ajax function or do I have to writte a custom method in the controller to reformat the data I receive in the params hash

1

There are 1 answers

0
dazonic On

I’ve used this jQuery plugin to do exactly this, I haven’t found an example of anyone doing it vanilla though.

https://github.com/marioizquierdo/jquery.serializeJSON