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

如何使用连接表中的rails将csv插入mysql?,mysql,ruby-on-rails,ruby,csv,ruby-on-rails-4,Mysql,Ruby On Rails,Ruby,Csv,Ruby On Rails 4,我有3个模型项目Gosts和项目\ Gosts 项目1.rb 如何使用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(;))

我有3个模型项目Gosts和项目\ Gosts 项目1.rb

如何使用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

好的,您可以通过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
def self.import(文件)
CSV.foreach(file.path,headers:true)do |行|
项目=项目。按项目id查找项目(第[“项目id”]行)
gosts=[]
行[“gost_名称”]。拆分(;)。每个行都有| gost_名称|

天哪,你在挣扎哪一点?从你的代码看,你几乎就要成功了。尽管此
gosts=Gost.find_或_create_by(name:row[“gosts_names”])。拆分(;)
将不起作用。您只是在尝试将gost分配给项目吗?是的,我只是在ItemGost表中创建字符串,其中item_id=csv中的item_id,gost_id=gosts_名称拆分;
class Gost < ActiveRecord::Base
    has_many :item_gosts
    has_many :items, through: :item_gosts
end
item_id,gosts_names
1,8734; 14-162-184-2150; 8758
2,8734; 14-161-184-2000; 8732
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
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