Rails如何查看关联的has_many模型的更改

时间:2018-05-04 13:03:55

标签: ruby-on-rails

我有BoatPrice型号。 has_many :prices。我需要跟踪prices的{​​{1}}关联的更改:

  • 当船的所有价格都被删除时

  • 或当一艘船以前没有价格而现在有一些

以下是我提出的代码:

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

1 个答案:

答案 0 :(得分:0)

我不知道它是否可以帮助你,但有一颗宝石audited。看看:https://rubygems.org/gems/audited。 它会记录您模型的所有更改,并且它适用于您的Rails版本!