如何在连接表中使用rails将csv插入mysql?

时间:2015-01-26 14:53:22

标签: mysql ruby-on-rails ruby csv ruby-on-rails-4

我有3个模型Items Gosts和Item_Gosts item.rb的

class Item < ActiveRecord::Base
    has_many :item_gosts
    has_many :gosts, through: :item_gosts
end

item_gost.rb

   class ItemGost < ActiveRecord::Base
          belongs_to :item
          belongs_to :gost
        end

gost.rb

class Gost < ActiveRecord::Base
    has_many :item_gosts
    has_many :items, through: :item_gosts
end

现在我需要将csv文件导入ItemGost表

ItemGost它是连接表并具有此结构 | id | item_id | gost_id |

我有带有item_id的csv文件和来自Gost.name的集合,它有这个结构

item_id,gosts_names
1,8734; 14-162-184-2150; 8758
2,8734; 14-161-184-2000; 8732

如何使用csv文件导入?

Gost.rb

def self.import(file)
      CSV.foreach(file.path, headers: true) do |row|
        item = Item.find_by_id(row["item_id"])
        gosts = Gost.find_or_create_by(name: row["gosts_names"].split(;))
        ?????
        item.save!
      end
    end

1 个答案:

答案 0 :(得分:0)

好的,所以你可以通过rails提供的关联方法来实现:

def self.import(file)
  CSV.foreach(file.path, headers: true) do |row|
    item = Item.find_by_id(row["item_id"])
    gosts = []
    row["gosts_names"].split(;).each do |gost_name|
      gosts << Gost.find_or_create_by(name: gost_name)
    end
    item.gosts = gosts 
    item.save!
  end
end