Created
September 12, 2014 18:43
-
-
Save dv/a34366e03d1ba4cb61ee to your computer and use it in GitHub Desktop.
Votable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/models/post | |
class Post < ActiveRecord::Base | |
include Votable | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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