I have a Photo object and an Activity observer.
Activities are basically just a listing of recent activities around the site (photo uploaded, comment made, etc).
Right now I have a before_destroy
method in the Activity observer so that when an object (such as a photo) is destroyed, it will remove the activity from the listing of recent activities.
But what I need to do is sort of fake the destroy action for the photo.
We don't actually destroy the record in the database when someone "deletes" their photo, we just mark it as inactive.
But since I'm using observers, how can I still trigger that before_destroy
method in the Activity observer when a user fires the Photo.destroy
method?
Here is the basic code for both the Photo object and the observer...
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
As you are updating the resource rather than deleting it, could you not use a before_update method?
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
I've not tested this but I hope you see what I mean.