如何从 Rails 中的 HABTM 连接表中删除条目?

发布于 2024-08-15 12:08:59 字数 96 浏览 5 评论 0原文

通过多次迭代测试,我注意到当这些模型的实例被删除时,代表两个模型之间 HABTM 关系的连接表并没有删除条目。删除具有 HABTM 关系的模型实例时,我是否需要执行一些特殊操作?

Through many iterations of testing, I just noticed that my join table that represents a HABTM relationship between two models isn't removing entries when instances of these models get deleted. Do I need to do something special when removing an instance of a model that has HABTM relationships?

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

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

发布评论

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

评论(2

余生共白头 2024-08-22 12:08:59

经过仔细检查,HABTM 关系应该删除连接表条目。但是,当您使用 delete 方法删除记录时,HABTM 关系或我在该解决方案的原始版本(请参阅帖子历史记录)中描述的关系都不会删除这些连接表条目。 ActiveRecord::Base#delete 不会触发任何回调,例如 HABTM 关系为从连接表中删除孤立条目而建立的回调。相反,您应该使用ActiveRecord::Base#destroy

您必须使用原始 SQL 来删除不需要的条目。如果您决定创建连接模型,则可以迭代连接模型中的条目,删除那些没有关联的条目。

例子:

class Foo < ActiveRecord::Base
  has_many :foo_bars, :dependent => :destroy
  has_many :bars, :through => :foo_bars
end

class FooBar < ActiveRecord::Base
  belongs_to :foo
  belongs_to :bar
end

class Bar < ActiveRecord::Base
  has_many :foo_bars, :dependent => :destroy
  has_many :foos, :through => :foo_bars
end

FooBar.all.each{|fb| fb.destroy? if fb.foo.nil? || fb.bar.nil? }

Upon closer inspection HABTM relationships should be removing join table entries. However neither HABTM relationships or the relationship I described in the original version (see post history) of this solution will remove those join table entries when you eliminate the record with the delete method. ActiveRecord::Base#delete does not trigger any callbacks, such as the ones a HABTM relationship establishes to remove orphaned entries from the join table. Instead you should be using ActiveRecord::Base#destroy.

You will have to use raw SQL to remove the unneeded entries. If you decide to create a join model, you can iterate through entries in the join model, deleting those without an association.

Example:

class Foo < ActiveRecord::Base
  has_many :foo_bars, :dependent => :destroy
  has_many :bars, :through => :foo_bars
end

class FooBar < ActiveRecord::Base
  belongs_to :foo
  belongs_to :bar
end

class Bar < ActiveRecord::Base
  has_many :foo_bars, :dependent => :destroy
  has_many :foos, :through => :foo_bars
end

FooBar.all.each{|fb| fb.destroy? if fb.foo.nil? || fb.bar.nil? }
枯叶蝶 2024-08-22 12:08:59

连接表中的条目应该被删除,而无需您执行任何特殊操作。如果遇到奇怪的情况,您可以将 :delete_sql 选项添加到代码中来更改行为。删除连接另一侧的对象不是默认行为。

The entries in the join table should be getting deleted without you doing anything special. You can add the :delete_sql option to your code to change the behavior if you have a weird situation. Deleting the object on the other side of the join is not a default behavior.

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