【问题标题】:Rails create data in has_many :through relationRails 在 has_many 中创建数据:通过关系
【发布时间】:2019-12-13 02:46:04
【问题描述】:

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

job.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

导入.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

我已将 City 和 Job 从 CSV 导入数据库。现在如何创建数据到 City_jobs 表来保留 city_id 和 jobs_id?请帮我!谢谢!

【问题讨论】:

  • 您的 CSV 文件中有什么?

标签: mysql ruby-on-rails ruby database foreign-keys


【解决方案1】:

您可以再次遍历 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

【讨论】:

  • 谢谢!我忘了显示 city_jobs 的迁移文件,我想在该表中创建记录。我已经编辑了我的帖子。你有什么想法吗?
  • 是的,city.jobs &lt;&lt; job 行创建了 CityJob 连接模型。或者,如果你想明确一点,你可以改用CityJob.create(city_id: city.id, job_id: job.id)
猜你喜欢
  • 1970-01-01
  • 2021-09-24
  • 1970-01-01
  • 1970-01-01
  • 2012-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-24
相关资源
最近更新 更多