简体   繁体   English

Rails- has_many:通过创建,删除和访问记录

[英]Rails- has_many :through create, delete and access records

Below code is from http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association 下面的代码来自http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association

class CreateAppointments < ActiveRecord::Migration
 def change
  create_table :physicians do |t|
   t.string :name
   t.timestamps null: false
  end

create_table :patients do |t|
  t.string :name
  t.timestamps null: false
end

create_table :appointments do |t|
  t.belongs_to :physician, index: true
  t.belongs_to :patient, index: true
  t.datetime :appointment_date
  t.timestamps null: false
end

end end 结束

In the above example how do i: 在以上示例中,我如何:

1) Create/destroy a relation between a physician and patient. 1)创建/销毁医师与患者之间的关系。 Do i just use: 我是否只使用:

Create: Appointment.create(physician_id, patient_id)
Destroy: (i have no clue hot to do this)

What is the correct way to do it? 正确的方法是什么?

2) How would i access all the appointment_date in the Appointment model for a particular patient or physician? 2)我将如何访问特定患者或医师的约会模型中的所有约会日期?

1/ 1 /

 Appointment.find_by(physician: @physician, patient: @patient).destroy

2/ 2 /

 @patient.appointments.pluck(:appointment_date)

You can create an appointment from either the physician or the patient, depending on your preference: 您可以根据自己的喜好从医生或患者那里创建约会:

@patient = Patient.find(params[:id])
@patient.appointments.create(physician: *object*, appointment_date: *datetime object*)  # auto sets the patient to match the @patient.id

#or from the physician
@physician = Physician.last #select the last physician
@physician.appointments.create(patient: *object*, appointment_date: *datetime object*) # auto sets the physician to match the @physician.id

If you have both ID's, you can also create it this way: 如果您拥有两个ID,也可以通过以下方式创建它:

Appointment.new(patient: *Patient object*, physician: *Physician object*, appointment_date: *datetime object*)

To destroy a record, just find the active record object and call destroy on it. 要销毁一条记录,只需找到活动的记录对象并在其上调用destroy。 Play around in console to see how it works. 在控制台中播放以查看其工作原理。 For instance: 例如:

Patient.find(id).appointments.last.destroy #destroys the last appointment for a patient with id

or find and delete an Appointment directly: 或直接查找并删除约会:

# find active record and then call destroy
@appointment = Appointment.find(1) # find appointment with ID: 1
@appointment.destroy

#call destroy directly by chaining commands
Appointment.find(1).destroy #does the exact same thing as above.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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