Rails 3.2 before_destroy摧毁有条件不射击的孩子

时间:2013-05-31 18:53:33

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

我有以下三种模式:

class Tag < AR::Base
  has_many   :mention_tags, dependent: :destroy
  has_many   :mentions, through: :mention_tags

  before_destroy :destroy_mentions

  def destroy_mentions
    mentions.each do |mention|
      mention.destroy if mention.tags.count == 1
    end
  end
end

class MentionTag < AR::Base
  belongs_to :tag
  belongs_to :mention
end

class Mention < AR::Base
  has_many    :mention_tags
  has_many    :tags,         through: :mention_tags
end

似乎destroy_mentions方法没有在标记计数为1的提及上调用.destroy,当该标记被销毁时我似乎无法找出原因。

这是一个过时的规范:

describe 'mention with this and other tags' do
  before do
    @tag1 = Tag.create(text: 'whatever', conditional: 'yes')
    @tag2 = Tag.create(text: 'whatever2', conditional: 'yes')
    @mention = Mention.create(text: 'whatever', tags: [@tag1, @tag2])
  end

  it 'should not delete the mention when deleting the tag' do
    @tag1.destroy
    Mention.exists?(id: @mention.id).should be_true
  end
end

此规范失败:

describe 'mention with only this tag' do
  before do
    @tag = Tag.create(text: 'whatever', conditional: 'yes')
    @mention = Mention.create(text: 'whatever', tags: [@tag])
  end

  it 'should delete the mention when deleting the tag' do
    @tag.destroy
    Mention.exists?(id: @mention.id).should be_false
  end
end

0 个答案:

没有答案