1

I have an array of objects which i'm sending to the controller through ajax.

My ajax request is like this:

$.ajax({
  data: {
    product: [{'name': 'ahmad', 'price': 'tench', 'quantity': '12'}, {'name': 'gulshan', 'price': 'tench', 'quantity': '12'}]
  },
  url: '',
  type: "POST",
  dataType: "json",
  success: function ( data ) {
    console.log(data);
    // this.setState({ comments: data });
  }.bind(this)
});

Controller:

def create
  @product = Product.new(product_params)
  if @product.save
    render json: @product
  else
    render json: @product.errors, status: :unprocessable_entity
  end
end

private

def product_params
  params.fetch(:product).permit!
end

But if i use create method then also i'm getting the same error.

I'm attaching a screenshot of the parameters in the rails log.

enter image description here

I dont understand why i'm getting this error?

Please help.

Ahmad hamza
  • 1,816
  • 1
  • 23
  • 46

2 Answers2

1

The issue you have is that since you're passing an array of products, your Rails' strong params are unable to determine the attributes to pass.

Strong params expects:

params: {
   product: {
     "name" => "Test"
   }
}

This way, when you require(:product).permit(:name), the strong params module will slice up the hash as required. Because your hash looks like the following, it is hitting a problem:

params: {
   product: [
     {"name" => "test"},
     {"name" => "test2"}
   ]
}

--

Might be worth looking at nested values:

params.permit(:product => [{:name, :price, :quantity}])
Richard Peck
  • 76,116
  • 9
  • 93
  • 147
0

So i tried many things but failed to do anything with it till this point.

product_arr = []
product_params.each_pair { |key, product| product_arr << product }
@products = Product.create(product_arr)

each_pair returns the response in keys and values.

Ahmad hamza
  • 1,816
  • 1
  • 23
  • 46