2011-09-22 88 views
1

我有以下的模型對象:如何鏈接兩個軌道查詢在一起優雅?

#<Insight id: 155, endorse_id: 15, supporter_id: 15, created_at: "2011-09-22 02:27:50", updated_at: "2011-09-22 02:27:50"> 

凡贊同的has_many見解和支持者有很多見解。

我可以查詢以下列方式分貝:

Endorse.find(15).insights.count

Insight.find_all_by_supporter_id(15).Count之間

如何優雅地鏈接這兩個查詢在一起,我可以搜索由Endorse 15創建的所有Insights,以及Suppor第15條?

回答

2
Rails2: 

insight_count = Insight.count(:conditions => {:supporter_id => 15, endorse_id => 15}) 
insights  = Insight.all(:conditions => {:supporter_id => 15, endorse_id => 15}) 

Rails3: 

insight_count = Insight.where(:supporter_id => 15, endorse_id => 15).count 
insights  = Insight.where(:supporter_id => 15, endorse_id => 15).all  
+0

優秀。謝謝 –

1

試試這個

對於Rails的3.0.x和3.1可能

Endorse.find(15).insights.find_all_by_supporter_id(15).count 

對於Rails的2.3.x版本

Endorse.find(15).insights.find_all_by_supporter_id(15).length 
0

我不知道你想鏈在一起因爲每一個都是不同的查詢。如果他們之間存在關係,那麼這對我來說是有意義的。例如,如果Endorse包含包含支持者的Insights。

+0

rwilliams答案是有意義的,如果你想從第一個查詢的結果中找到supporter_id = 15的所有見解......這看起來像你想從重讀最後一行帖子:) – nateleavitt