我怎么可以为了我的作品被总和从一个单独的表? [英] How can I order my entries by sum from a separate table?

查看:99
本文介绍了我怎么可以为了我的作品被总和从一个单独的表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道我怎么可以为了我的PostController中#指数帖子一列总在一个单独的表中显示。这是我如何把它建立起来。

I am wondering how I can order posts in my PostController#index to display by a column total in a separate table. Here is how I have it set up.

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

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

我的用户可以投票上涨或下跌某一职位。我知道有可能更好的方法去做我目前做的,但找给我的现状进行了修复。当用户投票起来后,为1的值被经由一个隐藏字段传递到投票表。当一个用户投票降值-1被传递给相同的列后(名投票)。

I user can either vote up or down a particular post. I know there are likely better ways to do what I am currently doing but looking for a fix given my current situation. When a user votes up a post, a value of 1 is passed to the Vote Table via a hidden field. When a user votes down a post a value of -1 is passed to the same column (names vote).

我想知道我怎么能显示我的职位,以便在投票栏(在投票表)之和为特定的职位。

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

另一种方式说,如果某一职位为5的净投一笔,我希望这种情况出现上述情况后与4的净投票总和

Another way to say that is, if a particular post has a net vote sum of 5, I want that to appear above a post with a net vote sum of 4.

我假设我需要影响PostController中#index动作以某种方式。但不知道该怎么做。

I am assuming that I need to affect the PostController#index action in some fashion. But not sure how to do that.

推荐答案

试试这个:

@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

这篇关于我怎么可以为了我的作品被总和从一个单独的表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆