2014-01-29 80 views
0

我可能有一個簡單的問題。我有以下三個表:從數據庫中刪除連接的表格

create_table "appointments", force: true do |t| 
t.integer "teacher_id" 
t.integer "student_id" 
t.datetime "start_date" 
end 

create_table "teachers", force: true do |t| 
t.string "name" 
end 

create_table "students", force: true do |t| 
t.string "email" 
t.string "first_name" 
t.string "last_name" 
end 

我已經做了以下型號的這三種類型的數據:

class Appointment < ActiveRecord::Base 
    belongs_to :teacher 
    belongs_to :student 
end 

class Teacher < ActiveRecord::Base 
    has_many :appointments 
    has_many :students, :through => :appointments 
end 

class Student < ActiveRecord::Base 
    has_many :appointments 
    has_many :teachers, :through => :appointments 
end 

所以,每次老師可以有很多不同的學生,每個學生可以在許多約會與不同的老師有許多約會。我的問題是如果管理員從數據庫中刪除該學生,如何刪除屬於某個學生的約會?

我認爲我正確建模這樣,但是當我刪除用戶這樣的,他的任命依然存在:

def destroy 
    Student.find(params[:id]).destroy 
end 

謝謝!

回答

1
class Student < ActiveRecord::Base 
    has_many :appointments, :dependent => :delete_all 
    has_many :teachers, :through => :appointments 
end 

delete_all不會調用在約會上定義的任何銷燬回調。但它是有效的,因爲問題單刪除查詢

+0

謝謝你,它的工作原理。正是我在找的東西:) – Cristiano