通过对另一个表中的值进行分组来创建订单表 [英] Order table by grouping values in another table

查看:124
本文介绍了通过对另一个表中的值进行分组来创建订单表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题表:title
每个问题在另一个表中有答案:text,question_id
每个答案在另一个表中有投票:answer_id

I have a table of questions: title Each question has answers, in another table: text, question_id Each answer has votes, in another table: answer_id

我可以要求总投票

question.votes.count

我已经看过如何将投票db分组到
http://guides.rubyonrails.org/active_record_querying.html#group

I have seen how to group the votes db at http://guides.rubyonrails.org/active_record_querying.html#group

Vote.group("answer_id")

但我想订购我的问题投票。这是通过另一个表的分组从表中排序数组。这是可能吗?

But I want to order my questions by votes. That is ordering an array from a table via the grouping of another table. Is that possible?

q=Question.last
q.answers.order_by_vote #How to do this?

我想我的答案可能是在回答模型上做一个范围,投票属于这个问题。对不对?

I think my answer could be doing a scope on the answer model that makes the grouping on the subset of votes that belong to the question. Am I right?

谢谢。

推荐答案

通过投票计数,使用我的链接视图中的排序方法来组织我的链接:

I just figured out a way to organize my links by vote count, using the sort method in my links view:

<%@ user.links.sort {| a,b | b.votes.sum(:score)= a.votes.sum(:score)} .each do | link | %>

votes.sum(:score)从投票表中获取特定链接的投票数。

votes.sum(:score) grabs the number of votes a particular link has from the votes table.

希望有所帮助。

这篇关于通过对另一个表中的值进行分组来创建订单表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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