#ruby-on-rails #activerecord
Вопрос:
У меня есть две модели 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(amp;:mark_for_destruction)
expect(wheels_to_destroy.map(amp;: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
Кто-нибудь может помочь мне понять, что здесь происходит? Я в растерянности. Я использую Рельсы 5.2.4.
Комментарии:
1. я предполагаю
bicycle.wheels.where(flat: true)
, что возвращаю пустой список, иexpect([].map(amp;:marked_for_destruction?)).to all(eq(true))
он всегда передается.