Ruby on Rails:从嵌套参数中读取

时间:2015-10-16 07:33:18

标签: ruby-on-rails ruby parameters

我有这些参数:

  Parameters: {"controller"=>"parent_wise_fee_payments", "transaction_date"=>"2015-10-16", "action"=>"pay_payments", "id"=>"10", 
  "transactions"=>{"payment_mode"=>"Cash", 
  "1"=>{"payment_id"=>"54", "payment_mode"=>"Cash", "amount"=>"", "parent_id"=>"10", "payment_date"=>"2015-10-16", "title"=>"Second Payment", "payment_note"=>""}, 
  "0"=>{"payment_id"=>"53", "payment_mode"=>"Cash", "amount"=>"600000", "parent_id"=>"10", "payment_date"=>"2015-10-16", "title"=>"First Payment", "payment_note"=>""}, 
  "payment_note"=>""}, "authenticity_token"=>"6jbXWEjBnhQjbWpNiK4cCWPhr/NSDEwul6kH+XcKE/U="}

" 1"和" 0"没有修复,它们取决于交易的数量,所以我可能有3个交易,每个交易都有payment_id,payment_mode,amount,......

我只对获得每笔交易的价值感兴趣,即" 1"和" 0"。但我无法找到办法做到这一点。

这是我尝试的内容:

  params[:transactions].each do |payment|
        payment.each do |p|
            .... p[0][:amount]
end
end

这会产生错误,因为付款[0]是" payment_mode"只有1个值,付款[1]是" payment_note"。我无法访问" 1"和" 0",即使我尝试付款[" 0"] ["金额"]和付款[" 0"] [:金额我得到了"无法将字符串转换为整数"。我还尝试使用payment.keys检查密钥是否为" payment_mode"或" payment_note"然后丢弃它,但是我得到了"未定义的数组"方法键。我迷失在这里,我知道我搞砸了,但我真的需要你的帮助。

1 个答案:

答案 0 :(得分:1)

关键字“transactions”下的值又是一个哈希值,所以你需要迭代值和键。

这样做的一种方法是

# This works only in rails, not in plain ruby
payments = params["transactions"].except(["payment_mode", "payment_note"])
payments.each do |key, value|
    puts "key: " + key
    puts "values under that key: " + value
end

另见 https://repl.it/BRCs/2

在这种情况下,数字“0”,“1”将在变量“key”中,并且它们在“value”中保存的值。