【问题标题】:Rails CSV upload to update records - attribute not saved to dbRails CSV 上传以更新记录 - 属性未保存到数据库
【发布时间】:2013-12-18 02:00:10
【问题描述】:

我有一个使用 CSV 上传更新 InventoryItem 记录的系统。

我有这个控制器方法:

def import
        InventoryItem.import(params[:file], params[:store_id])
        redirect_to vendors_dashboard_path, notice: "Inventory Imported."
    end

Which of course calls this model method:

def self.import(file, store_id)
    CSV.foreach(file.path, headers: true) do |row|
    inventory_item = InventoryItem.find_or_initialize_by_code_and_store_id(row[0], store_id)
    inventory_item.update_attributes(:price => row.to_hash.slice(:price))
        end
    end

我只想更新更新中的:price 属性,因为:code:store_id 不会改变。目前正在导入的记录的价格都为 0.0(大十进制)。不是零,也不是正确的值,而是 0.0,所以很明显我做错了事情来完成这项工作。我知道当我在控制台中执行此操作时,它看起来像这样:

inventory_item = InventoryItem.find_by_id(1)
inventory_item.update_attributes(:price => 29.99)

关于为什么我没有正确更新价格属性的任何想法?

【问题讨论】:

标签: ruby-on-rails csv


【解决方案1】:

尝试一下,似乎 csv 不会返回符号化的哈希键 切片似乎在那里不起作用。这个在你的里面怎么样 CSV.foreach 循环:

inventory_item.update_attributes(:price => row.to_hash["price"])

【讨论】:

  • 对不起,不,在我的控制台示例中并不意味着暗示这一点。是小数。修正了那个例子。
  • 你是说如果:price 是小数,我应该打电话给to_f
  • 我是,但试过了,它不需要它。更新了我的答案以表明 csv 不返回符号哈希键。
  • 所以这行得通,但我不能说我明白为什么。似乎这只会更新价格(就像我想要的那样),但是["price"] 是如何做到这一点的呢?另外,我已经看到在其他 CSV 使用实例中使用切片,为什么这种情况不允许切片?感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多