Rails 4 - 导入CSV和空白值

时间:2015-06-05 22:38:47

标签: ruby-on-rails

我在Rail 4中有一个电子商务应用。有一个导入csv功能,允许我批量上传产品详细信息。每个产品都有价格和销售价格。价格是必填字段。售价是可选的。

当我导入一个已填充saleprice或未填充新产品(尚未在网站上)的文件时,它会按预期上传。由于saleprice字段在哈希中,当它为空时,它假定没有销售价格。这很好并且符合预期。

但是,当我想更新具有销售价格的产品以取消销售价格时,它不会删除销售价格。如果我将saleprice放在像:saleprice => row['SalePrice'].to_i,这样的哈希值之外,那么它将售价显示为0美元(当它是空白时)

当saleprice为空白时,我希望它假设没有销售价格,所以忽略它。

list_hash

中其他字段的行为相同

感谢帮助。

这是代码:

# model
validates :saleprice, numericality: {greater_than: 0}, :allow_blank => true

def importcsv(file_path, user_id)

    open(file_path) do |f|
            CSV.parse(f.read , headers: true, skip_blanks: true) do |row|

          listing_hash = {:name => row['Product_title'], 
                          :made_to_order => row['Made_to_order'],
                          :description => row['Description'],
                          :sku => row['Product_ID'],
                          :price => row['Price'].to_i,
                          :category => row['Category'].titleize, 
                          :inventory => row['Quantity_in_stock'].to_i,
                          :image => URI.parse(row['Image']),
                          :user_id => user_id}.tap do |list_hash|
                            list_hash[:designer_or_brand] = row['Designer_or_Brand'] if row['Designer_or_Brand'] 
                            list_hash[:saleprice] = row['SalePrice'].to_i if row['SalePrice'] 
                            list_hash[:image2] = URI.parse(row['Image2']) if row['Image2'] 
                            list_hash[:image3] = URI.parse(row['Image3']) if row['Image3'] 
                            list_hash[:image4] = URI.parse(row['Image4']) if row['Image4'] 
                                end

          listing = Listing.where(sku: listing_hash[:sku], user_id: listing_hash[:user_id]) 

          if listing.count == 1 
            listing.first.update_attributes(listing_hash)
          else
            Listing.create!(listing_hash)
          end 

      end

0 个答案:

没有答案