Reputation: 353
I'm working on posting data from a React Form to a Ruby on Rails API, about the React part, if just send the first item from an array using this code:
const submitOrderHandler = async (userData) => {
setIsSubmitting(true);
await fetch("http://localhost:3000/ordertemps", {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(cartCtx.items[0]),//please include user: userData
});
setIsSubmitting(false);
setDidSubmit(true);
cartCtx.clearCart();
};
The Ruby on Rails API manage it and store it in the table, this is the output:
However, I need to store all the data selected by the user, so, to accomplish this task I updated my code like this:
const submitOrderHandler = async (userData) => {
const dataSelected = JSON.stringify(cartCtx.items);
console.log(dataSelected);
setIsSubmitting(true);
await fetch("http://localhost:3000/ordertemps", {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(cartCtx.items),//please include user: userData
});
setIsSubmitting(false);
setDidSubmit(true);
cartCtx.clearCart();
};
The problem is I'm getting a 400 Status, so this is how the data looks from the FrontEnd:
This is the output from the Ruby on Rails Endpoint:
the source code of the Controller in charge to manage and store the data is this:
#POST /ordertemps
def create
@ordertemp = Ordertemp.new(ordertemp_params)
if @ordertemp.save
render json: @ordertemp
else
render error: { error: 'Unable to create an order'}, status: 400
end
end
private
def ordertemp_params
#params.require(:ordertemp).permit( :clientName, :clientId, :amount, :mealid, :name, :price)
params.require(:ordertemp).permit(:name, :amount, :price)
end
So, I'm assuming these facts:
My question is: what am I missing in my controller to store all the data sent by the FrontEnd?
Thanks a lot for your comments
Upvotes: 0
Views: 520
Reputation: 642
Update your controller code as below:
#POST /ordertemps
def create
begin
params['_json'].each do |ordertemp_params|
@ordertemp = Ordertemp.new(ordertemp_params)
@ordertemp.save
end
head :no_content
rescue => e
render json: { error: unable to create orders }, status: 400
end
end
Hope this will help you.
Upvotes: 1