我正在通过ajax提交数据以插入数据库。
由于 View 和表单的复杂性,我发送了一些冗余信息(两个表单合并为一个)。
例如我发送的数据是
partner_id:940
partner_ref: 1
product_1_id:50
product_1_quantity:1
然后,在我的 Controller 中,我提交除 partner_id
和 partner_ref
之外的所有内容,为此,我正在计算 POST
数组的大小,减去 2 来说明我不想存储的 2 个参数,然后将其除以 2 以获得实际存储的产品数量,因此结果应该为 1,但表中存储了 2 个条目。
# get number of parameters passed and subtract 2 for partner_id and partner_ref
# divide count by two to get actual number of line items
line_items = ((params.size - 2) / 2)
count = 1
for i in count..line_items
item_id = params["product_#{count}_id"]
quantity = params["product_#{count}_quantity"]
# had to add this conditional statement to prevent NULL entries in the database
if !item_id.nil? and !quantity.nil?
line_item = QuoteItem.create(:price_list_item_id => item_id, :quantity => quantity)
end
count = count + 1
end
render :text => line_items # => 2 when it should be 1
这肯定是一些愚蠢的事情,但看不出有什么问题。
最佳答案
rails 默认情况下记录的参数不是整个 params
哈希。例如,在我的应用程序中,如果我进行搜索,我会看到 Rails 默认记录的以下参数:
Parameters: {"utf8"=>"✓", "term"=>"searchterm"}
但是如果我记录在 params
哈希上调用 inspect
的结果,我会得到:
{"utf8"=>"✓", "term"=>"searchterm", "action"=>"search", "controller"=>"home"}
这是因为 Rails 使用 params
哈希将 Controller 和操作名称存储在 params
哈希中。正如您所评论的,在某些 (POST) 表单上,您还会添加 CSRF 参数。
您最好看看 Rails 如何将参数解释为数组和哈希。正如 MrYoshiji 所评论的,如果您使用 products[][id]
,rails 会将其转换为哈希数组。您还可以使用显式数组引用作为位置。
因此,对于文本字段标记(指定值以更清楚地说明):
text_field_tag("products[][id]", "1")
text_field_tag("products[][quantity]", "11")
text_field_tag("products[][id]", "2")
text_field_tag("products[][quantity]", "22")
您的参数将包含如下产品值:
"products"=>[{"id"=>"1", "quantity"=>"11"}, {"id"=>"2", "quantity"=>"22"}]
这意味着您无需计算任何内容,只需迭代产品并处理它们即可:
params["products"].each do |product_hash|
product_hash["id"] # The id
product_hash["quantity"] # The quantity
end
关于ruby-on-rails - 计算 Rails 中 POST 数组的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18615988/