У меня есть модель Boat
и Price
. A Лодка has_many :prices
. Мне нужно отслеживать изменения prices
ассоциации boat
:
Вот код, который я придумал:
class Boat < ApplicationRecord
has_many :prices, dependent: :destroy
def priceable_changed?
prices_deleted || prices_created
end
def prices_created
prices.any? && prices.map {|p| p.saved_changes? }.all?
end
def prices_deleted
prices.empty? && prices.select { |p| p.destroyed? }.any?
end
end
Однако кажется, что в некоторых случаях это работает, а в других - нет
# Create a boat with no prices
> boat = FactoryBot.create(:boat)
> boat.priceable_changed? => FALSE # OK
# Add a previously created price to a boat
> price = FactoryBot.create(:price, boat: boat)
> boat.priceable_changed? => FALSE # NOT OK
# Create a price to the boat
> boat.prices.create
> boat.priceable_changed? => TRUE # OK
# Create a boat with prices
> boat = FactoryBot.create(:boat, :with_3_prices)
> boat.priceable_changed? => FALSE # OK
# Delete one price
> boat.prices.last.destroy
> boat.priceable_changed? => FALSE # OK
# Delete all prices at once
> boat.prices.destroy_all
> boat.priceable_changed? => FALSE # NOT OK
# Delete all prices one by one
> boat.prices.map(&:destroy)
> boat.priceable_changed? => TRUE # OK
Есть ли надежный способ сделать это? Я чувствую, что делаю все неправильно ...
Я использую Rails 5.2
.