简体   繁体   中英

How can I manipulate data on a has_many :through Association on ActiveRecords on Ruby on Rails?

The documentation is a little poor in this aspect. If I have this tables

 Physicians Table
-----------
id integer
name string

Appointments table
----------------
id integer
physician_id integer
patient_id integer
appointment_date datetime

Patients table
---------------
id integer
name string 

and this models:

class Physician < ActiveRecord::Base
  has_many :appointments
  has_many :patients, :through => :appointments
end

class Appointment < ActiveRecord::Base
  belongs_to :pshysician
  belongs_to :patient
end

class Patient < ActiveRecord::Base
  has_many :appointments
  has_many :pshysicians, :through => :appointments
end

how do I do to insert an appointment on the database? It's not clear at all in the Rails webpage

This is a quite broad question actually. To insert a record in the database you can do one of three things.

  1. Appointment.create(patient_id: 1, physician_id: 1, apt_date: DateTime.now)

  2. If you have an instance of the Patient model lets call it patient and you want to assign in to physician with id=2 then

    patient.appointments.create(physician_id: 2, apt_date: DateTime.now)

  3. If you have an instance of the Physician model called physician then

    physician.appointments.create(patient_id: 10, apt_date: DateTime.now)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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