Rails CSV上传以更新记录-属性未保存到数据库 [英] Rails CSV upload to update records - attribute not saved to db

查看:89
本文介绍了Rails CSV上传以更新记录-属性未保存到数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a system for updating InventoryItem records using a CSV upload.

我有这个控制器方法:

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(大十进制).不是nil,也不是正确的值,而是0.0,所以很显然我在做些错误的事情来使这项工作有效.我知道当我在控制台中执行此操作时,它看起来像这样:

I want to update only the :price attribute in the update because and :code and :store_id won't change. Currently the records being imported have price all as 0.0 (big decimal). Not nil, or the correct value, but 0.0, so clearly I'm doing something wrong to make this work. I know when I do this in the console it looks something like this:

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

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

Any ideas on why I'm not updating the price attribute correctly?

推荐答案

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

Trying this, it doesn't seem like csv returns symbolized hash keys and slice doesn't seem to work there. how about this inside your CSV.foreach loop:

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

这篇关于Rails CSV上传以更新记录-属性未保存到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆