简体   繁体   中英

Rails create data in has_many :through relation

I have these file and a CSV file. Now I want to

job.rb

class Job < ApplicationRecord
  has_many :city_jobs
  has_many :cities, through: :city_jobs
end

city.rb

class City < ApplicationRecord
  has_many :city_jobs
  has_many :jobs, through: :city_jobs
end

city_jobs.rb

class CityJob < ApplicationRecord
  belongs_to :city
  belongs_to :job
end

migration files

    create_table :jobs do |t|
      t.string :title
      t.string :level
      t.string :salary
      t.string :other_salary
      t.text :description
      t.text :short_des
      t.text :requirement
      t.integer :category
      t.datetime :post_date
      t.datetime :expiration_date
      t.references :company, foreign_key: true

      t.timestamps
    end

    create_table :cities do |t|
      t.string :name, unique: true
      t.string :region

      t.timestamps
    end


    create_table :city_jobs do |t|
      t.references :city, foreign_key: true
      t.references :job, foreign_key: true

      t.timestamps
    end

Import.rb require "csv"

class JobsImport
  def import_job
    jobs = []
    cities = []

    job_columns = [:title, :level, :salary, :description, :short_des,
                   :requirement, :category, :company_id]
    city_columns = [:name, :region]

    CSV.foreach(Rails.root.join("lib", "jobss.csv"), headers: true) do |row|
         cities << {name: row["company province"], region: "Việt Nam"}
         jobs << JobCsv.new(row).csv_attributes
    end

    City.import city_columns, cities, on_duplicate_key_ignore: true
    Job.import job_columns, jobs
    puts "Data imported"
  end
end

I have imported City and Job from CSV to database. Now how can I create data to City_jobs table that keep cities_id and jobs_id? Please help me! Thank you!

You can iterate through the CSV file again to connect the two tables.

CSV.foreach(Rails.root.join("lib", "jobss.csv"), headers: true) do |row|
     city = City.find_by(name: row["company province"])
     job = Job.find_by(JobsCsv.new(row).csv_attributes)
     city.jobs << job
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM