在rails中,如何在不删除真实记录的情况下销毁“连接表项”?

时间:2021-12-08 01:20:16

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 Shcema < AcitveRecord::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?

如果我只想破坏关系项,我该怎么办?

2 个解决方案

#1


6  

If you want to delete all tasks in sc:

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

sc.tasks.delete_all

If you want to delete a specific task in sc:

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

我希望有所帮助。

#2


1  

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

如果要删除连接表中的所有记录,例如amenities_lodgings而不使用任何对象,则可以使用:

ActiveRecord::Base.connection.execute("DELETE  from amenities_lodgings")

#1


6  

If you want to delete all tasks in sc:

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

sc.tasks.delete_all

If you want to delete a specific task in sc:

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

我希望有所帮助。

#2


1  

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

如果要删除连接表中的所有记录,例如amenities_lodgings而不使用任何对象,则可以使用:

ActiveRecord::Base.connection.execute("DELETE  from amenities_lodgings")