Skip to content

Instantly share code, notes, and snippets.

@uberllama
Last active December 28, 2015 13:09
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save uberllama/7505705 to your computer and use it in GitHub Desktop.
Observer example 2
# config/application.rb
config.autoload_paths << "#{config.root}/app/models/observers"
config.active_record.observers = :trackable_observer
# app/models/comment.rb
class Comment < ActiveRecord::Base
belongs_to :user
has_many :activities, as: :trackable
end
# app/models/like.rb
class Like < ActiveRecord::Base
belongs_to :user
has_many :activities, as: :trackable
end
# app/models/activity.rb
class Activity < ActiveRecord::Base
belongs_to :user
belongs_to :trackable, polymorphic: true
end
# app/models/observers/user_observer.rb
class TrackableObserver < ActiveRecord::Observer
observe :comment, :like
def after_create(trackable)
trackable.activities.create(user_id: trackable.user_id)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment