I need to store the bellow parameter into a table:
[{"id":"1","name":"Cheese and red deans","amount":2,"price":"0.65"},{"id":"2","name":"Pork, cheese and red beans","amount":2,"price":"0.85"},{"id":"3","name":"Soda","amount":1,"price":"0.65"}]
The controller's code is this (I'm using ActiveController):
#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
However, I'm getting an error in the next code:
private
def ordertemp_params
params.require(:ordertemp).permit(:name, :amount, :price)
end
I found the method permit is just related to hashes, so apparently my data is not in that format, so I tried to use different functions such as: .each_with_index.to_a, to_h, Hash but nothing seems to work.
So my questions are:
- what function should I use to convert my data to a hash?
- Do I need to iterate my data in order to save each item into the table?
Thanks a lot
CodePudding user response:
You need to add more to your question. Go to your web console and copy the actual params being submitted. Also what exactly are your errors?
You can look at this: https://codersloth.medium.com/rails-creating-multiple-records-from-a-single-request-a45261085164 as it covers much of what you are talking about. I'm guessing here because of your lack of info in your question but this might work:
def create
begin
OrderTemp.transaction do
@ordertemp = Ordertemp.create!(ordertemp_params)
end
rescue ActiveRecord::RecordInvalid => exception
# omitting the exception type rescues all StandardErrors
@ordertemps = {
error: {
status: 422,
message: exception
}
}
end
render json: @ordertemp
end
And in your params method:
private
def ordertemp_params
params.permit(:name, :amount, :price)
end