Rails通过关系计算

时间:2012-03-03 02:06:17

标签: ruby-on-rails activerecord relationship

我在解决这个问题时遇到了问题。

我有四个模型:Account有很多 - > List有很多 - > ListItem< -belongs to Category

我需要获取前n个类别和数量计数的列表 - 与ListItem s最相关的列表。为了使其更复杂,帐户有一个“角色”(比如“团队领导”和“经理”,计数需要由该角色分开。总而言之,我需要这个:

Top 5 Categories for Team Lead: Category122 (74), Category342 (67), Category22 (52), Category992 (50), Category12 (47) 
Top 5 Categories for Manager: Category1 (174), Category32 (112), Category22 (88), Category92 (73), Category5 (72) 

我一直试图形成范围或编写类方法来生成这些数字,并且在我感到困惑之前不要走远。

任何人都知道如何计算这类事物?

2 个答案:

答案 0 :(得分:1)

将此添加到您的Account型号:

has_many :list_items, :through => :lists

然后你可以这样做:

a = Account.first
a.list_items.joins(:category).group("categories.name").count
# => {"foo"=>1, "bar"=>2}

修改

@categories = Category.select("categories.name AS name, accounts.role AS role, count(list_items.id) AS count")
.joins(:list_items => {:list => :account})
.group("categories.name, accounts.role")
.order("count desc")
.limit(5)

@categories[0].role
# => Team Leader
@categories[0].count
# => 5

您必须将类别字段添加到选择中,查询类似于:

SELECT categories.name, accounts.role, count(list_items.id) 
FROM list_items INNER JOIN lists ON lists.id = list_items.list_id 
INNER JOIN categories ON categories.id = list_items.category_id 
INNER JOIN accounts ON lists.account_id = accounts.id 
GROUP BY categories.name, accounts.role;

答案 1 :(得分:0)

您可以尝试这样的事情:

top_team_lead_categories = Category.all(
  :joins => {:list_item => {:list => :account}},
  :select => "categories.*, sum(if(list_items.category_id = categories.id, 1, 0)) as list_items_count",
  :conditions => ['accounts.role =?', 'team lead'],
  :group => 'categories.id',
  :order => 'list_items_count desc'
)