Skip to content

Instantly share code, notes, and snippets.

@dv
Created September 12, 2014 18:43
Show Gist options
  • Save dv/a34366e03d1ba4cb61ee to your computer and use it in GitHub Desktop.
Save dv/a34366e03d1ba4cb61ee to your computer and use it in GitHub Desktop.
Votable
# app/models/post
class Post < ActiveRecord::Base
include Votable
end
# app/models/concerns/votable.rb
module Votable
extend ActiveSupport::Concern
included do
has_many :votes
end
def update_vote_count!
update_attributes(vote_count: votes.size) if has_attribute?(:vote_count)
end
end
# app/models/vote
class Vote < ActiveRecord::Base
belongs_to :item, polymorphic: true
after_save :update_item_vote_count
private
def update_item_vote_count
if item.present?
item.update_vote_count!
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment