[英]Ruby: parameters in array format to hash format
我需要将波纹管参数存储到一个表中:
[{"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"}]
控制器的代码是这样的(我使用的是 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
但是,我在下一个代码中遇到错误:
private
def ordertemp_params
params.require(:ordertemp).permit(:name, :amount, :price)
end
我发现方法permit只与哈希有关,所以显然我的数据不是那种格式,所以我尝试使用不同的函数,例如:.each_with_index.to_a、to_h、Hash 但似乎没有任何效果。
所以我的问题是:
非常感谢
您需要在问题中添加更多内容。 Go 到您的 web 控制台并复制提交的实际参数。 还有你的错误到底是什么?
你可以看看这个: https://codersloth.medium.com/rails-creating-multiple-records-from-a-single-request-a45261085164因为它涵盖了你所说的大部分内容。 我猜这里是因为您的问题中缺少信息,但这可能有效:
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
在你的 params 方法中:
private
def ordertemp_params
params.permit(:name, :amount, :price)
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.