Module: FormalVote::ActsAsVoteable::SingletonMethods
- Defined in:
- lib/acts_as_votable.rb
Instance Method Summary collapse
- #column_names_for_tally ⇒ Object
-
#plusminus_tally(params = {}) ⇒ Object
(also: #rank_tally)
Calculate the plusminus for a group of voteables in one database query.
-
#tally(*args) ⇒ Object
Calculate the vote counts for all voteables of my type.
Instance Method Details
#column_names_for_tally ⇒ Object
59 60 61 |
# File 'lib/acts_as_votable.rb', line 59 def column_names_for_tally column_names.map { |column| "#{self.table_name}.#{column}" }.join(', ') end |
#plusminus_tally(params = {}) ⇒ Object Also known as: rank_tally
Calculate the plusminus for a group of voteables in one database query. This returns an Arel relation, so you can add conditions as you like chained on to this method call. i.e. Posts.tally.where(‘votes.created_at > ?’, 2.days.ago) You can also have the upvotes and downvotes returned separately in the same query: Post.plusminus_tally(:separate_updown => true)
29 30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/acts_as_votable.rb', line 29 def plusminus_tally(params = {}) t = self.joins("LEFT OUTER JOIN #{Vote.table_name} ON #{self.table_name}.id = #{Vote.table_name}.voteable_id AND #{Vote.table_name}.voteable_type = '#{self.name}'") t = t.order("plusminus_tally DESC") t = t.group(column_names_for_tally) t = t.select("#{self.table_name}.*") t = t.select("SUM(CASE #{Vote.table_name}.vote WHEN #{quoted_true} THEN 1 WHEN #{quoted_false} THEN -1 ELSE 0 END) AS plusminus_tally") if params[:separate_updown] t = t.select("SUM(CASE #{Vote.table_name}.vote WHEN #{quoted_true} THEN 1 WHEN #{quoted_false} THEN 0 ELSE 0 END) AS up") t = t.select("SUM(CASE #{Vote.table_name}.vote WHEN #{quoted_true} THEN 0 WHEN #{quoted_false} THEN 1 ELSE 0 END) AS down") end t = t.select("COUNT(#{Vote.table_name}.id) AS vote_count") end |
#tally(*args) ⇒ Object
Calculate the vote counts for all voteables of my type. This method returns all voteables (even without any votes) by default. The vote count for each voteable is available as #vote_count. This returns an Arel relation, so you can add conditions as you like chained on to this method call. i.e. Posts.tally.where(‘votes.created_at > ?’, 2.days.ago)
51 52 53 54 55 56 57 |
# File 'lib/acts_as_votable.rb', line 51 def tally(*args) t = self.joins("LEFT OUTER JOIN #{Vote.table_name} ON #{self.table_name}.id = #{Vote.table_name}.voteable_id") t = t.order("vote_count DESC") t = t.group(column_names_for_tally) t = t.select("#{self.table_name}.*") t = t.select("COUNT(#{Vote.table_name}.id) AS vote_count") end |