D
D
dexdev2015-01-26 17:59:48
MySQL
dexdev, 2015-01-26 17:59:48

How to import csv file into mysql join table using rails?

There are three models Item Gost ItemGosts

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

Item has already been imported, now it remains to import join table ItemGosts I don’t understand how, because Item can have several Gosts
There is a csv file with the following content
item_id,gosts_names
1,8734; 14-162-184-2150; 8758
2.8734; 14-161-184-2000; 8732
Where 1st column is Item.id and the second is Gost.name
I'm trying to do something like
ItemGost.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

But their brains are not enough.

Answer the question

In order to leave comments, you need to log in

1 answer(s)

item.gosts << gosts
Вроде так.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question