12

我现在很困惑,我不知道如何删除/销毁连接表中的记录:


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.

如果我只想销毁关系项,我该怎么办?

4

3 回答 3

7

如果要删除 sc 中的所有任务:

sc.tasks.delete_all

如果要删除 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

我希望这会有所帮助。

于 2011-08-03T20:25:19.207 回答
2

如果您想从连接表中删除所有记录,例如amenities_lodgings 不使用任何对象,您可以使用:

ActiveRecord::Base.connection.execute("DELETE  from amenities_lodgings")
于 2016-02-15T10:02:42.257 回答
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
于 2020-01-14T23:08:33.780 回答