How can I order my records by amount from a separate table?

I am wondering how I can order the posts in my PostController # index to be displayed by full column in a separate table. This is how I set it up.

class Post < ActiveRecord::Base
  :has_many :votes
end

      

and

Class Vote < ActiveRecord::Base
  :belongs_to :post
end

      

The user can either vote up or down on a particular entry. I know there are probably better ways to do what I am doing now, but look for a fix given the current situation. When a user votes for a message, the value 1 is passed to the voting table through a hidden field. When a user votes on a post, a value of -1 is passed to the same column (votes are being voted).

I am wondering how I can display my posts in the order of the sum of the voting column (in the vote table) for a specific position.

Another way of saying is that if a particular post has a net total of 5 votes, I want this to appear above the post with a total vote of 4.

I am guessing that I need to somehow influence the PostController # index action. But not sure how to do it.

+2


a source to share


2 answers


Try the following:



@posts = Post.all(:select => "posts.*, SUM(votes.vote) as vote_total",
         :joins => "LEFT JOIN votes AS votes ON votes.post_id = posts.id",
         :group => "posts.id",
         :order => "vote_total DESC")
@posts.each do |post|
  post.vote_total
end

      

+1


a source


You can use something like the following.



class Post < ActiveRecord::Base
  :has_many :votes
   named_scope :post_list, 
                :select=>" posts.id, posts.title,posts.description,  votes.total",       
                :joins => :votes, "LEFT JOIN votes ON posts.id = votes.post_id"
                :order => "votes.total DESC"

end

      

0


a source







All Articles