我试图将隐藏文本字段(动态创建的JavaScript对象)保存为数据库中的哈希记录。问题是记录是用空哈希值保存的。以下是我所做过的相关代码和错误:
表单代码:
<%= form_for(@bill, remote: true) do |f| %>
<div class="hidden">
<%= f.text_field :items %>
<%= f.text_field :total_amount %>
<%= f.submit %>
</div>
<% end %>
JavaScript代码:
// bill_items is the dynamically created object
var items = JSON.stringify(bill_items);
$('#bill_items').val(items); // Setting Input text value
$('#bill_total_amount').val(bill_total_amount);
$('form#new_bill').submit();
正在传递的参数:
Parameters: {"utf8"=>"✓",
"bill"=>{"items"=>"{\"bill_item_1\":{\"product\":\"vaseline 300 ml\",
\"unit_price\":\"215\",\"quantity\":\"1\",\"discount\":\"0.0\",
\"amount\":\"215\"}}", "total_amount"=>"215", "transaction_type"=>"Cash", "transaction_id"=>"some_id"}}
控制器代码:
def create
@bill = Bill.new(bill_params)
if @rec_saved = @bill.save
respond_to do |f|
f.js
end
else
render 'new'
end
end
private
def bill_params
params.require(:bill).permit(:total_amount,
:transaction_type, :transaction_id, :items => {})
end
型号代码:
class Bill < ApplicationRecord
serialize :items, Hash
end
在bill_params
方法附近的控制器中使用调试器给出:
Unpermitted parameter: items
Return value is: nil
从控制台创建记录时,它运行正常。
我搜索并尝试了一些建议,但没有一个有效。我做错了什么?
答案 0 :(得分:0)
我认为问题是items
param有一个字符串值,而你是允许哈希。
首先,如果项目中有多个对象,请将其设为数组:
Parameters: {"utf8"=>"✓", "bill"=>{"items"=>"[{\"product\":\"name\",\"unit_price\":10},{\"product\":\"name2\",\"unit_price\":100}]", "total_amount"=>"215", "transaction_type"=>"Cash", "transaction_id"=>"some_id"}}
这样你就可以允许数组中对象的键:
private
def bill_params
params[:bill][:items] = JSON.parse(params[:bill][:items])
params.require(:bill).permit(
:total_amount, :transaction_type, :transaction_id, items: [:product, :unit_price]
)
end