我有以下三个模型:
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
当该标签被销毁时,该方法似乎没有调用.destroy
标签计数为 1 的提及,我似乎无法弄清楚原因。
这是一个传递规范:
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