来自belongs_to的recerence_id不会更新销毁其父级

时间:2014-07-16 18:57:55

标签: ruby-on-rails activerecord

我有一个拥有self belongs_to的模型:

class SyncType < ActiveRecord::Base
  belongs_to :sync_type, touch: true
  has_many :sync_types, -> { order('created_at ASC') }
end

我在数据库中保存了2个objets:

 #<SyncType id: 99, description: "test", sync_type_id: nil, created_at: "2014-07-16 18:49:09", updated_at: "2014-07-16 18:49:09">
 #<SyncType id: 95, description: "haha", sync_type_id: 99, created_at: "2014-07-16 18:31:48", updated_at: "2014-07-16 18:31:48">

所以,我需要获取所有不为我的公司提供父级的SyncType:

@sync_types_tree = SyncType.where("sync_type_id is null")

但是当我销毁id为99的对象时,它的引用不会更新id为95的对象(sync_type_id:99)。我该怎么做才能刷新它?当我销毁它时,我想把sync_type_id:nil。

根据导轨指南,&#34; touch:true,&#34;这可行,但不是。

http://guides.rubyonrails.org/association_basics.html#touch

我的临时解决方案:

@sync_types_to_destroy.each do |sync_to_destroy|
  sync_to_destroy.sync_types.each do |child|
    child.sync_type = nil
    child.save
  end
  sync_to_destroy.destroy
end

如果你有更好的主意,请帮助我:P

2 个答案:

答案 0 :(得分:2)

在has_many关联上设置:dependent选项:

has_many :sync_types, -> { order('created_at ASC') }, dependent: :nullify

现在,当您销毁父记录时,子项将使其sync_type_id属性无效。

sync_type = SyncType.where("sync_type_id is null").first
sync_type.destroy

使用您的示例记录,执行以下SQL:

BEGIN
UPDATE `sync_types` SET `sync_types`.`sync_type_id` = NULL WHERE `sync_types`.`sync_type_id` = 99 ORDER BY created_at ASC;
DELETE FROM `sync_types` WHERE `sync_types`.`id` = 99;
COMMIT

答案 1 :(得分:1)

您可以创建一个before_destroy回调,删除其他记录上的链接。

class SyncType < ActiveRecord::Base
  before_destroy :remove_links

  private 
  def remove_links
    SyncType.where('sync_type_id = ?', id).update_all(sync_type_id: nil)
  end
end
相关问题