1

我一直在关注 rails cast 剧集Importing CSV and excel,但我的设置略有不同。

我有两个模型,用法(数量)和价格(数量)。我已经设置好了,所以使用 has_one price 和 price belongs_to a usage。在我的 csv 中,我有两列,如下所示:

usage,price
1000,0.1
1500,0.11

我正在尝试导入数据,以便将usage.amount 和usage.price.amount 获取到我的数据库中。

我看了一下here,并尝试了那里的一切。需要注意的一件事是我没有 id 列(尽管我尝试使用 id 列并且该问题的代码仍然无效)。

这是我模型中的代码:

class Usage < ActiveRecord::Base
  has_one :price, dependent: :destroy

  accepts_nested_attributes_for :price


  def self.import(file)
    CSV.foreach(file.path, headers: true) do |row|
      Usage.create! row.to_hash
    end
  end
end

注意:我知道上面没有提到导入 price.amount,但是我尝试过的任何东西都行不通。

对此的任何帮助将不胜感激,谢谢!

更新

以下是我的工作方式:(感谢alalani帮助编写以下代码。)

CSV.foreach(file.path, headers: true) do |row|
  u = Usage.create(amount: row[0])
  u.create_price(amount: row[1])
end
4

1 回答 1

2

为什么不简单地创建类的新实例并手动添加呢?

所以你可以这样做:

def self.import(file)    
    CSV.foreach(file.path, headers: true) do |row|
        u = Usage.new(:amount => row[0])
        u.save
        p = Price.new(:amount => row[1])
        p.save
        u.price << p
    end
end

这似乎需要更多的工作,但很容易理解这里发生了什么

于 2013-02-18T14:07:44.330 回答