2015-11-17 108 views
1

下面的代碼是從http://guides.rubyonrails.org/association_basics.html#the-has_many-through-associationRails-的has_many:通過創建,刪除和訪問記錄

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)我如何訪問特定患者或醫生的預約模型中的所有約會?

+0

我使用創建目前正在創建的關係。至於銷燬我一直在銷燬控制檯上的記錄。 (我很抱歉,如果這真的很基礎) – fox

+0

我剛剛在另一個問題上發現了以下問題以創建關係:@ course.topics << Topic.new(params [:topic]) – fox

+0

您的代碼段僅分配給一個名爲'@ course'的臨時變量的新主題。因此,儘管該主題現在是「@ course」的一部分,並且可以通過「@ course.topics」訪問,但並沒有持久的關係。 –

回答

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

要銷燬一條記錄,只需找到活動記錄對象並對其進行銷燬即可。在控制檯中玩耍,看看它是如何工作的。例如:

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. 
+0

謝謝。如果我想摧毀一個特定的關係,我可以使用@Statyx的方法:@ patient.appointments.pluck(:appointment_date)或者你有不同的方式來做到這一點? – fox

+0

採摘不是一種破壞記錄的方法。它提取特定的字段。看看我的最後一行代碼。只要確保你有對你想刪除的ActiveRecord的引用,並調用它的destroy方法。我會在我的回答中澄清。 –

+0

已更新的答案。 –

1

1/

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

2/

@patient.appointments.pluck(:appointment_date) 
+0

非常感謝! – fox

相關問題