简体   繁体   English

Rails 在 has_many 中创建数据:通过关系

[英]Rails create data in has_many :through relation

I have these file and a CSV file.我有这些文件和一个 CSV 文件。 Now I want to现在我想

job.rb工作.rb

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

city.rb城市.rb

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

city_jobs.rb 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"导入.rb 需要“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.我已将 City 和 Job 从 CSV 导入到数据库。 Now how can I create data to City_jobs table that keep cities_id and jobs_id?现在如何将数据创建到 City_jobs 表中,以保留 city_id 和 jobs_id? Please help me!请帮我! Thank you!谢谢!

You can iterate through the CSV file again to connect the two tables.您可以再次遍历 CSV 文件以连接两个表。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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