Cristiano
Cristiano

Reputation: 3189

Delete connected tables from database

I have probably one simple question. I have the following three tables:

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

I have made the following models for these three type of data:

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

So, every teacher can have many appointments with many different students and every student can have many appointments with different teachers. My question is how to delete an appointments which belong to some student if administrator deletes that student from database?

I thought I modeled this correctly but when I delete user like this, his appointments are still there:

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

Thank you!

Upvotes: 0

Views: 86

Answers (1)

usha
usha

Reputation: 29349

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

delete_all will not call any destroy callbacks defined on appointment. but it is efficient because issues a single delete query

Upvotes: 1

Related Questions