Skip to content

Instantly share code, notes, and snippets.

@hara-y-u
Last active January 9, 2025 14:24
Show Gist options
  • Save hara-y-u/f581f5ce32f5bb8247036ac94fc5a25e to your computer and use it in GitHub Desktop.
Save hara-y-u/f581f5ce32f5bb8247036ac94fc5a25e to your computer and use it in GitHub Desktop.
Separation of Concerns with Rails ActiveRecord custom callbacks
module Commentable
extend ActiveSupport::Concern
included do
has_many :comments
define_model_callbacks :comment_update, only: :after
end
end
class Post
include Commentable
after_comment_update { touch(:comment_updated_at) }
end
class Comment
belongs_to :commentable, polymorphic: true
after_update { commentable.run_callbacks(:comment_update, :after) }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment