当关系的任何一方被销毁时,自引用has_many并删除连接记录

时间:2013-06-21 15:00:29

标签: ruby-on-rails ruby-on-rails-3

我有Board型号。对于其他Board,每个Source可以是Board。此关系保存在Feed表格中。

class Board < ActiveRecord::Base
  belongs_to :user
  has_many :links, dependent: :destroy
  has_many :feeds, dependent: :destroy
  has_many :sources, through: :feeds

  attr_accessible :description, :name, :user_id

  validates :name, presence: true
end

class Feed < ActiveRecord::Base
  belongs_to :board
  belongs_to :source, class_name: "Board"

  attr_accessible :board_id, :source_id

end

当我销毁Board记录时,它会销毁相应的feeds。但是对于source

,如何做同样的事情呢?

1 个答案:

答案 0 :(得分:0)

为什么不使用:dependent => :destroy

阅读Deleting from associations:has_many,has_one和belongs_to关联支持:dependent选项

如果这不起作用,您也可以使用ActiveRecord Callbacks:

after_destroy do |record| 
 other = BoardsSources.find_by_board_id_and_source_id(record.board_id, record.source_id)
 other.destroy if other
end