Sha256: 326ac1af3a8ede25c6a48f2a6dc943a91a3ba3aeb2118f45bfd88c474ad09ea9

Contents?: true

Size: 789 Bytes

Versions: 10

Compression:

Stored size: 789 Bytes

Contents

module FlexibleFeeds
  class Vote < ActiveRecord::Base
    belongs_to :event
    belongs_to :voter, polymorphic: true

    validates :value, inclusion: { in: [-1, 1] }, presence: true
    validates :event, presence: true
    validates :voter, presence: true

    after_save :calculate_event_stats
    after_destroy :calculate_event_stats

    def self.cast_vote(params)
      vote = find_by(voter: params[:voter], event: params[:event])
      return create(params) if vote.nil?
      vote.toggle_by_value(params[:value])
    end

    def toggle_by_value(submitted_value)
      if value == submitted_value
        destroy
      else
        update_attributes(value: submitted_value)
      end
    end

    private
    def calculate_event_stats
      event.calculate_stats
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
flexible_feeds-0.4.0 app/models/flexible_feeds/vote.rb
flexible_feeds-0.3.6 app/models/flexible_feeds/vote.rb
flexible_feeds-0.3.5 app/models/flexible_feeds/vote.rb
flexible_feeds-0.3.4 app/models/flexible_feeds/vote.rb
flexible_feeds-0.3.3 app/models/flexible_feeds/vote.rb
flexible_feeds-0.3.2 app/models/flexible_feeds/vote.rb
flexible_feeds-0.3.1 app/models/flexible_feeds/vote.rb
flexible_feeds-0.3.0 app/models/flexible_feeds/vote.rb
flexible_feeds-0.2.1 app/models/flexible_feeds/vote.rb
flexible_feeds-0.1.0 app/models/flexible_feeds/vote.rb