First StackOverFlow post, so bear with me :)
So I have a Post Model which has a Polymorphic Association with a Vote Model.
My main problem is ordering each post by the highest Votes. I'm trying to implement an Upvote system. QUESTION: How Do I Order Post by the Highest Votes? (@total)
It seems I have code in my views (@upcount, @downcount, @total) that I might perhaps have in my controller but I just have no clue how to do that.
Ideally I would want to do something like this in the community action : Post.order("@total") but obviously that won't work.
Post Model
class Post < ActiveRecord::Base
belongs_to :user
has_many :votes, :as => :votable
Vote Schema:
t.integer "upvote"
t.integer "downvote"
t.string "votable_type"
t.integer "votable_id"
t.integer "user_id"
Post Controller:
def community
@post = @votable = Post.all
end
And in My View Page (here's where things get tricky):
<% @post.each do |post| %>
<div class="eachpostrate">
<% if signed_in? then %>
<%= form_for [post, Vote.new] do |f| %>
<%= f.hidden_field :downvote, :value => "0" %>
<%= f.hidden_field :upvote, :value => "1" %>
<%= f.submit "8", :class => "upvotethumbup" %>
<% end %>
<% if post.votes.empty? then %>
<span class="upvotecount">
<p> 0 </p>
</span>
<% else %>
<% @upcount = [] %>
<% @downcount = [] %>
<span class="upvotecount">
<p>
<% post.votes.each do |vote| %>
<% @upcount << vote.upvote %>
<% @downcount << vote.downvote %>
<% end %>
<% @total = @upcount.sum - @downcount.sum %>
<%= @total %>
</p>
</span>
<% end %>
I solved this using the directions that nilbus provided with the exception of putting the score method in my Post Model instead of Vote Model
def score
self.votes.upvotes.count - self.votes.downvotes.count
end
Otherwise, my posts are now ordered according to Upvote! Thanks everyone!