I have the following model object:
#<Insight id: 15开发者_如何学编程5, endorse_id: 15, supporter_id: 15, created_at: "2011-09-22 02:27:50", updated_at: "2011-09-22 02:27:50">
Where Endorse has_many insights and Supporter has many insights.
I can query the db in the following way:
Endorse.find(15).insights.count
Insight.find_all_by_supporter_id(15).count
How can I elegantly chain both of these queries together where I can search for all Insights created by Endorse 15, and Supporter 15?
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
Try this
For Rails 3.0.x and probably 3.1
Endorse.find(15).insights.find_all_by_supporter_id(15).count
For Rails 2.3.x
Endorse.find(15).insights.find_all_by_supporter_id(15).length
I'm not sure you would want to chain them together since each one is a different query. If there were relationships between them, then it would make sense to me. For example, if Endorse contained Insights which contained Supporters.
精彩评论