0

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

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

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

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

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

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

4

2 回答 2

0

我在 Rails 3.1 中使用它。

当我删除一个文档时,所有相关的 DocumentFoo 也被删除。

class Document < ActiveRecord::Base
  has_many :document_foos

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

兄弟,乔纳斯

于 2011-11-21T12:45:56.497 回答
0

像下面这样的东西应该可以达到你想要的效果。请记住,我没有运行或测试过这段代码。

class Bar < ActiveRecord::Base

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

  def delete_orphan(foo)
    foo.destroy
  end

end

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

于 2011-06-16T15:10:33.020 回答