0

我已经尝试了一段时间来找到查询所需结果的最佳方法,但我总是在查询中的某些地方失败。

简化的数据库结构:

用户:

id (integer)  
first_name (string)  
last_name (string)

课程类型:

title (string)
slug (string)

课程:

belongs_to :user  
belongs_to :course_type  
week (integer)  
sold (float)

我的控制器正在调用一个范围:

@users = User.sales_results(week)

这是我模型中的范围:

scope :sales_results, lambda { |week|
  joins(:courses => [:course_type])
  .select("
    users.id, users.first_name, users.last_name,
    SUM(courses.sold) as total_sold,
    COUNT(courses) as num_classes
  ")
  .where("courses.week = ?", week)
  .group('users.id')
}

这很好用,我可以在我的模板中使用它来显示销售总额。虽然我还想显示第二列,其中总结了某些特定类型课程的销售价值。像这样:

<% @users.each do |user| %>
  <%= user.total_sold %>
  <%= user.total_sold.where("course_types.slug IN ('H', 'S')") # not possible, but similar to what I desire %>
<% end %>

更新

我最终添加了另一个范围

  scope :sales_results_for_types, lambda { |week, types|
     sales_results(week).except(:group).where("course_types.slug IN (?)", types)
    .group('users.id')
  }

然后在我的控制器中调用两个范围

@users = User.sales_results(...)
@users_filtered = User.sales_results_for_types(...)

最后同时迭代两个结果

<% @users.zip(@users_filtered).each do |user, filtered| %>
<%= filtered.total_sold %>
<%= user.total_sold %>

直到我想出更好的东西。感谢大家带领我走上正轨。

4

1 回答 1

0

如果您可以接受另一个查询,您可以使用它

user.joins(courses: :course_type).sum(:sold, group: 'course_types.slug')

这将为您提供一个散列,其中键是 slug,值是总和。

于 2013-02-01T15:03:23.280 回答