12

I get confuse now, I don't know how to delete/destroy a record in a join table:


class Task < ActiveRecord::Base
  belongs_to :schema
  belongs_to :to_do
end

class Todo < ActiveRecord::Base
  belongs_to :schema
  has_many :tasks
end

class Schema < ActiveRecord::Base
  has_many :todos
  has_many :tasks, :through => :todos
end

>> sc = Schema.new
>> sc.tasks << Task.new
>> sc.tasks << Task.new
>> sc.tasks << Task.new
...
>> sc.tasks.delete(Task.first) # I just want to delete/destroy the join item here.
# But that deleted/destroyed the Task.first.

What can I do if I just want to destroy the relation item?

Joshua Pinter
  • 45,245
  • 23
  • 243
  • 245
Croplio
  • 3,433
  • 6
  • 31
  • 37

3 Answers3

7

If you want to delete all tasks in sc:

sc.tasks.delete_all

If you want to delete a specific task in sc:

sc.tasks.delete_at(x) where x is the index of the task

or

sc.tasks.delete(Task.find(x)) where x is the id of Task

I hope that helps.

patsanch
  • 441
  • 3
  • 7
2

If you want to delete all records from join table like amenities_lodgings without using any object you can use:

ActiveRecord::Base.connection.execute("DELETE  from amenities_lodgings")
Jai Chauhan
  • 4,035
  • 3
  • 36
  • 62
1

Delete All Join Records

If you want to delete all the join records, you can use .clear:

>> sc = Schema.new
>> sc.tasks << Task.new
>> sc.tasks << Task.new
>> sc.tasks << Task.new
>> sc.tasks.size #=> 3
>> sc.tasks.clear
>> sc.tasks.size #=> 0
Joshua Pinter
  • 45,245
  • 23
  • 243
  • 245