【问题标题】:Finding the sum of a specific column inside hash查找哈希内特定列的总和
【发布时间】:2015-11-11 01:53:16
【问题描述】:

我正在将一个 .tab 文件上传到数据库,上传完成后一切顺利,我想仅从该上传而不是从整个表中计算商品价格。我将在下面发布我的示例。我将发布一个简单的,以在较小的范围内展示我正在尝试做的事情,然后我将发布我的上传操作,它只是试图在操作结束时获得特定的总和。

简单示例:

def find_whole_rev
  @total_price = NewTable.sum[:item_price]
end

返回表中所有值的总和没有问题。但要将其缩小以仅显示我所拥有的上传文件的商品价格:

 def import
   require 'csv'

   db = []
   CSV.parse(params[:file].read, {headers: true, col_sep: "\t"}) do |f|

    db.push(f.to_hash)
    NewTable.create(purchaser_name:  f.to_hash["purchaser name"],
                   item_description: f.to_hash["item description"],
                   item_price:       f.to_hash["item price"],
                   purchase_count:   f.to_hash["purchase count"],
                   merchant_address: f.to_hash["merchant address"],
                   merchant_name:    f.to_hash["merchant name"],

    ) 
       @upload_price = f.to_hash.sum[:item_price]
   end  
 end

一切都很好,除了我无法让 upload_price 变量填充上传文件的项目总价格。我收到此错误消息:

no implicit conversion of Symbol into Integer

感谢您的任何建议,如果需要,我会编辑/发布更多信息,没问题。再次感谢和欢呼!

【问题讨论】:

    标签: mysql ruby-on-rails file-upload methods sum


    【解决方案1】:
     def import
       require 'csv'
    
       db = []
       @upload_price = 0
    
       CSV.parse(params[:file].read, {headers: true, col_sep: "\t"}) do |f|
    
        parsed_hash = f.to_hash
    
        db.push(parsed_hash)
        NewTable.create(purchaser_name:  parsed_hash["purchaser name"],
                       item_description: parsed_hash["item description"],
                       item_price:       parsed_hash["item price"],
                       purchase_count:   parsed_hash["purchase count"],
                       merchant_address: parsed_hash["merchant address"],
                       merchant_name:    parsed_hash["merchant name"],
    
        ) 
    
        @upload_price += parsed_hash["item price"]
       end  
     end
    

    【讨论】:

    • 谢谢,我从 line:::::::: @upload_price += parsed_hash["item price"] 收到此错误,无法将字符串强制转换为 Fixnum
    • @upload_price += parsed_hash["item price"].to_i
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-07
    • 2015-08-22
    • 2010-11-26
    • 2017-08-02
    • 1970-01-01
    • 2012-01-14
    • 2017-02-23
    相关资源
    最近更新 更多