How to order an array with a variable view

StackOverFlow's first post, so carry me :)

So, I have a Post model that has a polymorphic association with the voting model.

My main problem is to arrange each message with the highest Votes. I am trying to implement the Upvote system. QUESTION: How do I order messages with the highest votes? (@total)

It seems that I have the code in my views (@upcount, @downcount, @total), which I probably have in the controller, but I just don't know how to do this.

Ideally, I would like to do something like this in a community action: Post.order ("@total"), but obviously this will not work.

Post model

class Post < ActiveRecord::Base 
belongs_to :user
has_many :votes, :as => :votable

Voting Scheme:

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 on my browse page (here, where things get complicated):

     <% @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 %>

, , nilbus , , Post- Vote Model

 def score 
self.votes.upvotes.count - self.votes.downvotes.count 
  end

Upvote! !

+3
2

, downvotes total Post. , , , . , , .

, , .

class Vote < ActiveRecord::Base
  scope :upvotes, where(:upvote => 1)
  scope :downvotes, where(:downvote => 1)
end

.

upvotes = post.votes.upvotes.count
downvotes = post.votes.downvotes.count
total = post.votes.count

, downvotes upvotes.

class Vote < ActiveRecord::Base
  def score
    upvotes.count - downvotes.count
  end
end

, , , .

@posts = @posts.sort_by(&:score)

. include . .

def community
  @post = @votable = Post.includes(:votes).all
end

, - (@post @votable)?

+3
posts.sort {|x, y| (x.votes.collect(&:upvote).size - x.votes.collect(&:downvote).size) <=> (y.votes.collect(&:upvote).size - y.votes.collect(&:downvote).size) }
+1

All Articles