:dependent => :destroy会破坏不再依赖的记录

时间:2016-02-18 01:09:53

标签: ruby-on-rails postgresql relational-database

在PostgreSQL上运行的Rails 4.2

我正在重构我的数据库并移动一些数据。每个ProgressUpdate都属于LanguageProgress。在迁移中,我将一些ProgressUpdates从一个LanguageProgress移动到另一个LanguageProgress,然后我销毁不再有任何关联ProgressUpdates的{​​{1}},但是销毁会触发销毁曾经依赖它的ProgressUpdates!为什么?

以下是迁移中的相关代码:

LanguageProgress.find_each do |lp|
  if existing_lp = LanguageProgress.find_by(progress_marker: lp.progress_marker, language_id: lp.state_language.language_id)
    puts "LanguageProgress #{existing_lp.id} has these ProgressUpdates: #{existing_lp.progress_updates.pluck :id}"
    puts "LanguageProgress #{lp.id} has these ProgressUpdates: #{lp.progress_updates.pluck :id}"
    lp.progress_updates.each do |pu|
      pu.language_progress = existing_lp
      pu.save!
    end
    puts "now LanguageProgress #{existing_lp.id} has these ProgressUpdates: #{existing_lp.progress_updates.pluck :id}"
    puts "and LanguageProgress #{lp.id} has #{lp.progress_updates.count} ProgressUpdates"
    puts "destroying LanguageProgress #{lp.id}"
    lp.destroy
  else
    lp.language_id = lp.state_language.language_id
    lp.save!
  end
end

以下是打印出来的内容:

LanguageProgress 1073685945 has these ProgressUpdates: [1071256240]
LanguageProgress 1073691483 has these ProgressUpdates: [1071256239]
now LanguageProgress 1073685945 has these ProgressUpdates: [1071256239, 1071256240]
and LanguageProgress 1073691483 has 0 ProgressUpdates
destroying LanguageProgress 1073691483
destroying ProgressUpdate 1071256239

以下是language_progress.rb

的相关位
class LanguageProgress < ActiveRecord::Base

  belongs_to :language
  belongs_to :state_language
  belongs_to :progress_marker
  has_many :progress_updates, dependent: :destroy

  validates :progress_marker, presence: true, uniqueness: { scope: :state_language }
  validates :state_language, presence: true

progress_update.rb

class ProgressUpdate < ActiveRecord::Base

  belongs_to :user
  belongs_to :language_progress
  delegate :language, to: :language_progress

  validates :progress, presence: true, inclusion: ProgressMarker.spread_text.keys
  validates :month, presence: true, inclusion: 1..12
  validates :year, presence: true, inclusion: 2000..Time.now.year
  validates :user, presence: true
  validates :language_progress, presence: true

  before_destroy{ |pu| puts "destroying ProgressUpdate #{pu.id}" }

end

1 个答案:

答案 0 :(得分:1)

猜测一下,我会在移动其他进程后(并在销毁之前)重新加载lp

实例变量可能包含对它认为仍属于它的进程的引用(即使它们不再执行)。