假摧毁行动?

时间:2012-03-15 12:18:02

标签: ruby-on-rails ruby-on-rails-3 observer-pattern

我有一个Photo对象和一个Activity观察者。

活动基本上只是网站上最近活动的列表(照片上传,评论等)。

现在我在Activity观察器中有一个before_destroy方法,这样当一个对象(例如照片)被销毁时,它将从最近活动的列表中删除该活动。

但我需要做的就是假装照片的破坏动作。

当有人“删除”他们的照片时,我们实际上并没有销毁数据库中的记录,我们只是将其标记为无效。

但由于我正在使用观察者,当用户触发before_destroy方法时,如何在Activity观察者中触发Photo.destroy方法?

以下是Photo对象和观察者的基本代码......

class PhotosController < ApplicationController
  def destroy
    @photo.update_attribute(:active, false)
  end
end


class ActivitySourceObserver < ActiveRecord::Observer
  observe :photo

  def before_destroy(activity_source)
    Activity.destroy_all(:activity_source_id => activity_source.id)
  end
end

2 个答案:

答案 0 :(得分:1)

选择你的毒药:AR soft delete

答案 1 :(得分:1)

在更新资源而不是删除资源时,您是否可以使用 before_update 方法?

class PhotosController < ApplicationController
  def destroy
    @photo.update_attribute(:active, false)
  end
end

class ActivitySourceObserver < ActiveRecord::Observer
  observe :photo

  def before_update(activity_source)
    if activity_source.has_attribute? :active && activity_source.active == false
      Activity.destroy_all(:activity_source_id => activity_source.id)
    end
  end
end

我没试过这个,但我希望你能明白我的意思。

相关问题