Rails 在 has_many :through 关系中创建数据



>我有这些文件和一个CSV文件。现在我想

工作.rb

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

城市.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

迁移文件

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 需要"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

我已将城市和作业从CSV导入数据库。现在,如何为保持cities_id和jobs_id City_jobs表创建数据?请帮帮我!谢谢!

您可以再次循环访问 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

相关内容

  • 没有找到相关文章

最新更新