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

vd8tlhqk  于 2023-03-08  发布在  Ruby
关注(0)|答案(1)|浏览(111)

我试图弄清楚如何手动设置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

*患者.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

*图表.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")
gg58donl

gg58donl1#

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

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")

相关问题