Noam B.
Noam B.

Reputation: 3250

Rails - Delete rows from a non indexed table

I have a connection table that connects between 2 tables. It has 2 columns: user_id and course_id. The name of the table is: course_sub_managers. This table does not have an index. So, how do I delete all rows that meet a condition in which course_id = certain variable? As for now I use:

sql = "DELETE FROM course_sub_managers WHERE course_id = " + @course.id.to_s
ActiveRecord::Base.connection.execute(sql)

Is there a Rails way to write it?

Upvotes: 2

Views: 185

Answers (2)

Hugo Logmans
Hugo Logmans

Reputation: 2252

It sounds you just want to handle the deletion of a course? Use the :dependent => :destroy on your relationships.

has_many :course_sub_managers, :dependent => :destroy

It will automatically remove the related table items when you destroy a course.

Upvotes: 0

Albin
Albin

Reputation: 3032

I suspect you have an course model where you have written something like:

has_many :course_sub_managers
has_many :users, through => :course_sub_managers

in that case you can use:

@course.course_sub_managers.delete_all

Upvotes: 1

Related Questions