Rails Active Record查询计数多个关系

时间:2014-04-16 17:06:55

标签: mysql sql ruby-on-rails activerecord

我有一个像这样的数据库:

  • 群组has_many包
  • 套餐has_many客房
  • 客房has_and_belongs_to_many客户

确定。每个房间都可以是“四人”,“三人”,“双人”等。我可以通过Group.rooms访问属于集团的所有房间。

我希望能够获得集团每种房型的客户数量。

例如:

  • Quad:16位客户
  • 双倍:10个客户 *等

我设法获得每种类型的房间数量,如下所示:

Group.rooms.group('type').count

有什么想法吗?

更新1 - 模型

Quarto.rb(Rooms)

class QuartoContratado < ActiveRecord::Base
    belongs_to :pacote
    has_and_belongs_to_many :clientes, :join_table => :acomodacoes

Pacote.rb(包裹)

class Pacote < ActiveRecord::Base        
    belongs_to :grupo
    has_many :passageiros
    has_many :clientes, :through => :passageiros
    has_many :quartos, :class_name => "QuartoContratado"

Grupo.rb(群组)

class Grupo < ActiveRecord::Base
    has_many :pacotes
    has_many :clientes, :through => :pacotes, :conditions => { :pacotes => { :cancelado => false } }
    has_many :quartos, :class_name => "QuartoContratado", :through => :pacotes, :conditions => { :pacotes => { :cancelado => false } }

Client.rb(客户)

class Cliente < ActiveRecord::Base
    has_many :passageiros
    has_many :pacotes, :class_name => "Pacote", :through => :passageiros
    has_many :grupos, :through => :pacotes, :conditions => { :pacotes => { :cancelado => false } }

1 个答案:

答案 0 :(得分:0)

这就是我设法得到我想要的东西......它看起来很难看!有没有更好的方法来写它?

group = Grupo.first
types = group.quartos.group_by { |t| t.type }

types.each do |key, value|
   print "#{key} - "
   c=0
   value.each do |v|
    c= c+v.clientes.count
   end
   puts "#{c} clients"
 end