2014-04-16 78 views
1

我有構造這樣一個數據庫:Rails的活動記錄查詢計數多重關係

  • 組的has_many包
  • 軟件包的has_many客房
  • 客房has_and_belongs_to_many客戶

確定。每個房間都可以是「四倍」,「三倍」,「雙倍」等。我可以通過Group.rooms訪問屬於某個組的所有房間。

我希望能夠獲得集團擁有的每個房間類型的客戶數量。

例如:

  • 四:16個客戶
  • 雙:10個客戶 *等。

我設法讓每種類型客房的ammount的,就像這樣:

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

任何想法?

更新1 - 型號

Quarto.rb(客房)

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 } } 
+0

繼續併發布您的所有模型,以便我們可以看到實際的關係。 – Lumbee

+0

我已更新模型@Lumbee的問題 – Guido

回答

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