Ruby:如何手动设置一对多和多对多关系的种子数据以使用活动记录

问题描述 投票:0回答:1

我想知道如何手动设置我的 Seeds.rb 数据。有了这些数据,我试图连接以下关系:一个医生有很多病人,一个病人有一个医生,一个病人有很多图表,一个医生可以通过病人访问这些图表。

当我手动创建数据时,我不明白如何连接三个不同的模型。

  • 对于 Doctor.rb 模型:
class Doctor < ActiveRecord::Base
    has_many :patients
    has_many :charts , through: :patients
end
  • 医生移民
class CreateDoctors < ActiveRecord::Migration[6.1]
  def change
      create_table :doctors do |t|
        t.string :name , :speciality 
        t.integer :license_number
      end 
  end
end
  • Patient.rb 模型:
class Patient < ActiveRecord::Base
    belongs_to :doctor
    has_many :charts
end
  • 患者迁移
class CreatePatients < ActiveRecord::Migration[6.1]
  def change
    create_table :patients do |t|
      t.string :name , :gender, :description, :medication
      t.integer :age
      t.float :account_balance
      t.integer :doctor_id , chart_id
      
    end
  end
end
  • Chart.rb 模型
class Chart < ActiveRecord::Base
    belongs_to :patient
    belongs_to :doctor
end
  • 图表迁移
class CreateCharts < ActiveRecord::Migration[6.1]
  def change
        create_table :charts do |t|
          t.string  :chart
          t.integer :patient_id , :doctor_id
          
       
    end
  end
end

种子数据示例:(我不确定如何连接这三个)

Doctor.create(name: "Aaron Yan", speciality: "Marriage & Family "  , license_number: 85477)

Patient.create(name: "Danielle Marsh", age: 28, gender: "F", account_balance: 44.23 , description: "Panic Disorder, Insomnia", medication:"Tofranil 25 mg")

Chart.create(description: "this patient exhibits the following symptoms, treatment plan is etc")
ruby activerecord many-to-many one-to-many seeding
1个回答
0
投票

您好,欢迎来到 Stack overflow! 要创建相关数据,您只需将结果保存到变量并使用关系添加它们。例如:

doctor = Doctor.create(name: "Aaron Yan", speciality: "Marriage & Family "  , license_number: 85477)

patient = doctor.patients.create(name: "Danielle Marsh", age: 28, gender: "F", account_balance: 44.23 , description: "Panic Disorder, Insomnia", medication:"Tofranil 25 mg")

patient.charts.create(description: "this patient exhibits the following symptoms, treatment plan is etc")
© www.soinside.com 2019 - 2024. All rights reserved.