在 Rails 中,如何销毁“连接表项”?而不删除真实记录?

发布于 2024-09-16 18:39:11 字数 660 浏览 6 评论 0原文

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


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.

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

明明#如月 2024-09-23 18:39:11

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

我希望有所帮助。

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.

情愿 2024-09-23 18:39:11

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

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

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")
丿*梦醉红颜 2024-09-23 18:39:11

删除所有加入记录

如果要删除所有加入记录,可以使用.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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文