Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 使用作用域的高级Rails ActiveRecord查询_Sql_Ruby On Rails_Join_Rails Activerecord - Fatal编程技术网

Sql 使用作用域的高级Rails ActiveRecord查询

Sql 使用作用域的高级Rails ActiveRecord查询,sql,ruby-on-rails,join,rails-activerecord,Sql,Ruby On Rails,Join,Rails Activerecord,我一直在尝试寻找查询所需结果的最佳方法,但我总是在查询的某个点失败 简化的数据库结构: 用户: 课程类型: title (string) slug (string) 课程: belongs_to :user belongs_to :course_type week (integer) sold (float) 我的控制器正在调用作用域: @users = User.sales_results(week) 以下是我的模型中的范围: scope :sales_results, la

我一直在尝试寻找查询所需结果的最佳方法,但我总是在查询的某个点失败

简化的数据库结构:

用户:

课程类型:

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 %>
然后在我的控制器中调用两个作用域

@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 %>


直到我想出更好的办法。感谢各位引导我走上正确的道路。

如果您对另一个查询没有意见,您可以使用此查询

user.joins(courses::course\u type).sum(:sell,group:'course\u types.slug')


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

我认为您可能需要为in['H','S']定义一个范围,然后对数据库进行另一个查询。您可能能够在一个复杂的SQL中获取数据,但这可能涉及第二次连接表,这是一个更加复杂的连接条件。
@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 %>