活动记录:包含关联的组结果

时间:2016-05-03 15:10:30

标签: ruby-on-rails activerecord

我有这些关联

class Application (id, priority, registration_id, uni_id)
  belongs_to :registration
  belongs_to :uni
end


class Uni (id, name)
   has_many :applications
end

class Registration (id, fname, lname, total_points)
  has_many :applications, :dependent => :destroy
  has_many :unis, :through => :applications
end

现在我运行像

这样的查询
@registration = Registration.includes(:applications, :unis).where('applications.priority = ?', true).references(:applications).order(total_points: :desc)

到目前为止它还可以。这将输出具有

的注册
1. application priority true and 
2. order the registrations by total_points. 

现在我想获得有

的注册
1. application priority true 
2. order the registrations by total_points
3. group the registrations by uni id.

例如,uni id 1的注册应该在一个组中,并且应该按total_points排序,类似于uni id 2的注册应该在第二组中,并且应该按total_points排序,依此类推。我试着做下面这样的事情

@registration = Registration.includes(:applications, :unis).where('applications.priority = ?', true).references(:applications).group('unis.id').order(total_points: :desc)

但这并没有给我我想要的东西。我该如何更改查询以获得预期结果?

1 个答案:

答案 0 :(得分:0)

如果你想要的是,比如在值中使用uni_id键和应用程序的哈希,我不认为你可以使用ActiveRecord做到这一点但你可以使用group_by使用原生Ruby做到这一点Array上的方法:

@registration = Registration.includes(:applications, :unis).where('applications.priority = ?', true).references(:applications).order(total_points: :desc).to_a.group_by('unis.id')

但请注意这一点,因为您要将所有匹配的记录拉入内存。这可以迅速扩展到一个庞大的数据结构,所以无论你可以委托给db的任何计算,你都应该考虑这样做。

对于记录,您可能还需要考虑定义范围:

class Application (id, priority, registration_id, uni_id)
  belongs_to :registration
  belongs_to :uni

  scope :priority, ->{ where priority: true}
end

Registration.joins(:application).merge(Application.priority)

或作用域协会:

class Registration (id, fname, lname, total_points)
  has_many :applications, :dependent => :destroy
  has_many :unis, :through => :applications

  has_many :priority_applications, ->{ where priority: true }
end

Registration.includes(:priority_applications)