In rails, how to destroy a 'join table item' with out deleting the real record?
Asked Answered
F

3

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?

Frisky answered 30/8, 2010 at 23:41 Comment(0)
Z
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.

Zealot answered 3/8, 2011 at 20:25 Comment(0)
S
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")
Solemnity answered 15/2, 2016 at 10:2 Comment(0)
E
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
Empson answered 14/1, 2020 at 23:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.