我有一个模型,我将一些相关数据存储在这样的哈希中:
line_items_attributes"=>[{"major"=>"8762", "minor"=>"322", "description"=>"Engineering", "amount"=>"200000", "active"=>"1"}, {"major"=>"8762", "minor"=>"445", "description"=>"Tanks", "amount"=>"2100000", "active"=>"1"}, {"major"=>"8762", "minor"=>"500", "description"=>"Pipe, Valves & Fittings", "amount"=>"150000", "active"=>"1"}]
我这样做是为了避免其他相关模型等。
我在这个网站上玩这个原型:
无论如何,我想要所有'数量'值。我用谷歌搜索了一些解决方案但我对哈希的了解还不够清楚。
我试过了:
2.0.0-p247 :053 > line_items_attributes.inject(0) {|sum, hash| sum + hash["amount"]}
TypeError: no implicit conversion of String into Integer
from (irb):53:in `[]'
from (irb):53:in `block in irb_binding'
from (irb):53:in `each'
from (irb):53:in `inject'
from (irb):53
from /Users/dan/.rvm/gems/ruby-2.0.0-p247@global/gems/railties-4.0.0/lib/rails/commands/console.rb:90:in `start'
from /Users/dan/.rvm/gems/ruby-2.0.0-p247@global/gems/railties-4.0.0/lib/rails/commands/console.rb:9:in `start'
from /Users/dan/.rvm/gems/ruby-2.0.0-p247@global/gems/railties-4.0.0/lib/rails/commands.rb:64:in `<top (required)>'
from bin/rails:4:in `require'
from bin/rails:4:in `<main>'
我甚至尝试添加hash [“amount”]。to_i但是没有用。我认为我很亲密,但我确信我错过了一些比较有经验的人。
在旁注中我看到其他哈希表示法显示如下:
line_items_attributes“=&gt; [{major:”8762“,未成年人:”322“等对此有优势吗?
答案 0 :(得分:1)
这对我有用:
2.0.0p247 :028 > line_items_attributes = [{"major"=>"8762", "minor"=>"322", "description"=>"Engineering", "amount"=>"200000", "active"=>"1"}, {"major"=>"8762", "minor"=>"445", "description"=>"Tanks", "amount"=>"2100000", "active"=>"1"}, {"major"=>"8762", "minor"=>"500", "description"=>"Pipe, Valves & Fittings", "amount"=>"150000", "active"=>"1"}]
=> [{"major"=>"8762", "minor"=>"322", "description"=>"Engineering", "amount"=>"200000", "active"=>"1"}, {"major"=>"8762", "minor"=>"445", "description"=>"Tanks", "amount"=>"2100000", "active"=>"1"}, {"major"=>"8762", "minor"=>"500", "description"=>"Pipe, Valves & Fittings", "amount"=>"150000", "active"=>"1"}]
2.0.0p247 :036 > line_items_attributes.inject(0) {|sum, hash| sum += hash["amount"].to_i; sum}
=> 2450000
答案 1 :(得分:0)
D'哦!再看一遍后,我错过了存储数据的实际情况:
{"line_items_attributes"=>[{"major"=>"8762", "minor"=>"322", "description"=>"Engineering", "amount"=>"200000", "active"=>"1"}, {"major"=>"8762", "minor"=>"445", "description"=>"Tanks", "amount"=>"2100000", "active"=>"1"}, {"major"=>"8762", "minor"=>"500", "description"=>"Pipe, Valves & Fittings", "amount"=>"150000", "active"=>"1"}]}
所以现在我跑了这个:
Model.find(1).data["line_items_attributes"].inject(0) {|sum, hash| sum + hash["amount"].to_i}
一切都很好。我可能不需要以那种方式存储它,但我只是以原型教程为例。
感谢那些花时间看这个的人。我已经把它想出来了......等等。