删除时,delete_all不起作用

时间:2017-04-01 07:48:33

标签: ruby-on-rails

预期功能 - 删除asset_line_item时删除所有链接的asset_items。 (不使用destroy,destroy_all)。我正在使用postgres

使用以下模型:

    [0] => Array (
    [Program] => Array (
        [event_name] => Event Daily
        [keyword] => KVIP SHOWTIME
        [start_date] => 2017-04-07 12:00:00
        [end_date] => 2017-04-03 15:00:00
        [location] => Studio 1
        [slots] => 10
        [event_color] => #9a9aff
        [is_allday] => 1
        [repeat_program] => daily-weekly
        [repeat_every] => 1
        [repeat_days] => ,1,2,3,4,5,6
        [repeat_yearly] => 0
        [is_end] => 0
        )
    )
[1] => Array (
    [Program] => Array (
        [event_name] => NEWS
        [keyword] => KVIP NEWS
        [start_date] => 2017-04-30 05:30:00
        [end_date] => 2017-04-01 19:00:00
        [location] => Studio 4
        [slots] => 05
        [event_color] => #fb8979
        [is_allday] => 1
        [repeat_program] => monthly
        [repeat_every] => 0
        [repeat_days] => 
        )
    )
[2] => Array (
    [Program] => Array (
        [event_name] => ASAP
        [keyword] => KVIP ASAP
        [start_date] => 2017-12-31 12:00:00
        [end_date] => 2017-04-01 15:00:00
        [location] => Studio 10
        [slots] => 16
        [event_color] => #9a9aff
        [is_allday] => 1
        [repeat_program] => yearly
        [repeat_every] => 0
        [repeat_days] => 
        )
    )

这会导致asset_items保持不变,但所有asset_line_item列都设置为null。

class AssetLineItem < PurchaseLineItem

  has_many :asset_items
  ...

  after_destroy :destroy_cleanup

  private

  def destroy_cleanup
    asset_items.delete_all
  end
end

用上面的循环替换delete_all但是具有删除所有关联的asset_items的预期结果。

虽然我有工作代码,但我很好奇什么可能导致delete_all以这种方式行事?

2 个答案:

答案 0 :(得分:2)

仅在关联上调用delete_all会使引用无效。它与delete_all(:nullify)

相同
pry(main)> Booking.last.passengers.delete_all
  Booking Load (0.6ms)  SELECT  `bookings`.* FROM `bookings`  ORDER BY `bookings`.`id` DESC LIMIT 1
  SQL (2.8ms)  UPDATE `passengers` SET `passengers`.`booking_id` = NULL WHERE `passengers`.`booking_id` = 157
=> nil

您需要致电delete_all(:delete_all)以实际删除相关记录。

这是docs

或者为了获得理想的效果,您可以在AssetLineItem模型中添加以下行:

has_many :asset_items, dependent: :destroy

lakhvir kumar 提及。

您的destroy_cleanup回调也可以重构为:

  def destroy_cleanup
    asset_items.map(&:delete)
  end

以下是该主题的一些很好的链接:

delete_all vs destroy_all?

Rails :dependent => :destroy VS :dependent => :delete_all

答案 1 :(得分:0)

使用[String: Any]