我正在设计一个处理电子商务网站收据的控制器。这就是JSON params的样子:
{
"receipt": {
"items": {
"item1": {
"price": "22.11",
"quantity": "2",
"name": "Name",
"discount": 0.04
},
"item2": {
"price": 12.11,
"quantity": 1,
"name": "Name"
},
"item3": {
"price": 21.11,
"quantity": 1,
"name": "Name",
"discount": 0.14
}
},
"payment_type": "Credit Card",
"payment_provider": "Visa",
"paid_status": true,
"total": 22
}
}
items字段是数据库中的文本字段,我使用serialize
将其转换为hash:
serialize :receiptitems, Hash
我强有力的参数以这种方式定义:
params.require(:receipt).permit(:payment_type, :payment_provider, :paid_status, :total, items: params[:receipt][:items].try(:keys))
由于项目是动态生成的,我现在收到错误:
Unpermitted parameters: item1, item2, item3
我该如何解决这个问题?我尝试了tap
方法,但效果不佳。
答案 0 :(得分:1)
您需要添加
行accepts_nested_attributes_for :price, :quality, :name, :discount
http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html