【问题标题】:Trouble with cascading in Active Record modelsActive Record 模型中的级联问题
【发布时间】:2014-11-14 12:06:10
【问题描述】:

我的应用程序中有这些活动记录模型

class Artist < ActiveRecord::Base
   has_many :albums, :dependent => :delete_all, autosave: true
end

class Album < ActiveRecord::Base
   attr_accessor :album_artist
   has_many :tracks, :dependent => :delete_all, autosave: true
   has_many :covers, :dependent => :delete_all, autosave: true
   belongs_to :artist
end

class Track < ActiveRecord::Base
   belongs_to :album
end

class Cover < ActiveRecord::Base
   belongs_to :album
end

我正在尝试,在我的应用程序中,当我删除一个艺术家时,他的专辑,因此,他专辑的曲目和封面,在级联反应中被全部删除。

今天的实现方式,当我删除艺术家时,也只删除了专辑,在我的数据库中留下了孤儿记录。

我做错了什么吗?

【问题讨论】:

    标签: ruby activerecord


    【解决方案1】:

    你需要配置而不是:dependent =&gt; :delete_all

    :dependent => :destroy_all
    

    因为delete 将直接从数据库中删除其所有关联对象,而不调用它们的销毁方法(什么会破坏级联)。

    您可能想阅读 http://guides.rubyonrails.org/association_basics.html#belongs-to-association-reference 中的 4.1.2.4

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多