强制 ActiveScaffold 删除关联而不是将外键设置为 null

发布于 2024-11-15 16:06:02 字数 465 浏览 5 评论 0原文

我在 RoR 2.2 项目中使用 ActiveScaffold。我的应用程序中有两个模型:

class Foo << ActiveRecord::Base
 belongs_to :bar
end

class Bar << ActiveRecord::Base
 has_many :foos
end

当我编辑 Bar 实例时,属于该 bar 的所有 foo 实例都会显示在表单中,每个实例旁边都有一个“删除”按钮。

当我删除一个然后按“更新”按钮时,ActiveScaffold 现在将 Foo.bar_id 设置为 nil 并发出和更新语句,如 UPDATE foo set bar_id = null ...

有没有办法从数据库中删除关联(即delete foo where foo_id = ...)?

I am using ActiveScaffold in an RoR 2.2 project. I have two models in my app:

class Foo << ActiveRecord::Base
 belongs_to :bar
end

class Bar << ActiveRecord::Base
 has_many :foos
end

When I edit a Bar instance, all the foo instances that belong to that bar are displayed in the form with a Remove button next to each one.

When I remove one and then press the Update button, right now ActiveScaffold sets Foo.bar_id to nil and issues and update statement like UPDATE foo set bar_id = null ....

Is there a way to delete association from the database (i.e. delete foo where foo_id = ...) instead?

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

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

发布评论

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

评论(2

旧瑾黎汐 2024-11-22 16:06:02

像下面这样的东西应该可以达到您想要的效果。请记住,我尚未运行或测试此代码。

class Bar < ActiveRecord::Base

  has_many :foos, :dependent => :destroy, :after_remove => :delete_orphan

  def delete_orphan(foo)
    foo.destroy
  end

end

编辑:切换到更具体的回调

Something like the following should achieve the effect you're looking for. Keep in mind I haven't run or tested this code.

class Bar < ActiveRecord::Base

  has_many :foos, :dependent => :destroy, :after_remove => :delete_orphan

  def delete_orphan(foo)
    foo.destroy
  end

end

Edit: Switched to a more specific callback

黯然 2024-11-22 16:06:02

我在 Rails 3.1 中使用它。

当我删除文档时,所有关联的 DocumentFoo 也会被删除。

class Document < ActiveRecord::Base
  has_many :document_foos

  before_destroy { |record| DocumentFoo.destroy_all "document_id = #{record.id}" }
end

兄弟,
乔纳斯

I'm using this in Rails 3.1.

When I delete a Document, all the associated DocumentFoo's are also deleted.

class Document < ActiveRecord::Base
  has_many :document_foos

  before_destroy { |record| DocumentFoo.destroy_all "document_id = #{record.id}" }
end

Br,
Jonas

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