2017-01-23 114 views
0

記錄獲取計數我有一個記錄中的ID爲1,它的has_many乙記錄各自具有許多C.的使用嵌套的has_many

A(ID = 1)=> [B記錄] => [ ]

我需要得到C的計數給定A.

我敢肯定有東西做joins,組, or order` [每個b C記錄],但我不知道究竟是什麼。我需要一種在常量SQL操作中執行此操作的方法。沒有迭代查詢。

+0

可以加一些型號的例子? –

回答

1

喜歡的東西:

A.join(:b => :c).where(id: 1).count("c.id")

如果你已經擁有的A一個實例:

a.b.joins(:c).count("c.id")

+1

雖然所有三個答案給出了不同的工作解決方案,但這個對我來說似乎很清楚。 –

+0

實際上,這兩種解決方案都需要修復。我不認爲第二種解決方案甚至是可能的(a上沒有'b'方法)。 – Swards

+0

@Swards如果'a'' has_many:b'那麼''a''上有一個'b'方法 –

1

使用has_many :through association

class A < ActiveRecord::Base 
    has_many :bs 
    has_many :cs, through: :bs 
end 

class B < ActiveRecord::Base 
    belongs_to :a 
    has_many :cs 
end 

class C < ActiveRecord::Base 
    belongs_to :b 
end 

現在你可以這樣做:

a.cs.count 

如果有一對多通a.cs關聯的東西,你不會經常使用,你寧願把它添加到你的模型,那麼你可以使用merge代替:

C.joins(:b).merge(a.bs).count 
1

幾種方法

C.joins(:b).where(:bs => {:a_id => a.id}).count 

class A < ActiveRecord::Base 

    has_many :bs 
    has_many :cs, :through => :bs 

end 

# Then you can do this, nice and easy to read. 
# Use size, not count in case they are already loaded. 

a.cs.size 

甚至

A.where(:id => a.id).joins(:bs => :cs).count 
1

假設我有一個理由不創造有許多通過通過BS協會CS,我會做這樣的事情:

class A < ActiveRecord::Base 
    has_many :bs 
    # has_many :cs, through: :bs - this allows a.cs.size as has been noted here 
end 

class B < ActiveRecord::Base 
    has_many :cs 
    belongs_to :a 
end 

class C < ActiveRecord::Base 
    belongs_to :b 
end 


# you can always do this if you don't want to create the above association through bs: 
a.bs.flat_map(&:cs).size 
+0

請解釋你正在努力實現的目標。有問題嗎? –

+0

沒問題,只是用不同的角度回答原始問題。試圖通過Bs實現A的Cs計數。平面地圖是達到目的的另一種手段。 – jasonbuehler

+0

對不起Jasonbuehler,我昨晚在管理問題,我沒有意識到我已經搬進了管理員隊列,我評論,如果用戶的第一篇文章。再次抱歉。 –