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

时间:2015-11-17 20:49:05

标签: ruby-on-rails

以下代码来自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

端 端

在上面的例子中我如何:

1)创建/破坏医生和患者之间的关系。我只是使用:

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

这样做的正确方法是什么?

2)我如何访问特定患者或医生的约会模型中的所有appointment_date?

2 个答案:

答案 0 :(得分:1)

1 /

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

2 /

 @patient.appointments.pluck(:appointment_date)

答案 1 :(得分:1)

您可以根据您的偏好从医生或患者创建预约:

@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

如果你同时拥有这两个ID,你也可以这样创建:

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

要销毁记录,只需找到活动记录对象并在其上调用destroy。在控制台中玩,看看它是如何工作的。例如:

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

或直接查找和删除约会:

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