我有两个具有一对多关系的ActiveRecord模型,配置如下:
class Bicycle < ApplicationRecord
has_many :wheels, dependent: :destroy, autosave: true
accepts_nested_attributes_for :wheels, allow_destroy: true
end
class Wheel < ApplicationRecord
belongs_to :bicycle
# has a boolean attribute called "flat"
end
我有一些逻辑,我想标记删除多个轮子,然后在保存相关自行车时实际删除它们。
#mark_for_destruction
这似乎是一个完美的解决方案,但我似乎无法让它在父母的自行车被保存时摧毁相关的车轮。
我写了一个rspec测试作为一个健康检查,可以确认它只在最后一行失败:
describe 'mark_for_destruction' do
it 'should work' do
bicycle = FactoryBot.create(:bicycle) # also creates 2 wheels where the first has flat = true
expect(bicycle.wheels.count).to eq(2)
wheels_to_destroy = bicycle.wheels.where(flat: true)
wheels_to_destroy.each(&:mark_for_destruction)
expect(wheels_to_destroy.map(&:marked_for_destruction?)).to all(eq(true))
bicycle.save!
expect(bicycle.reload.wheels.count).to eq(1) # Fails - count is still 2
end
end
然而
这
测试完全通过:
describe 'mark_for_destruction' do
it 'should work' do
bicycle = FactoryBot.create(:bicycle)
expect(bicycle.wheels.count).to eq(2)
wheel = bicycle.wheels.first
wheel.mark_for_destruction
expect(wheel.marked_for_destruction?).to eq(true)
bicycle.save!
expect(bicycle.reload.wheels.count).to eq(1)
end
end
有人能帮我理解这里发生了什么吗?我不知所措。我使用的是Rails 5.2.4。