Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何将两个rails查询优雅地链接在一起?_Ruby On Rails_Activerecord_Count_Find - Fatal编程技术网

Ruby on rails 如何将两个rails查询优雅地链接在一起?

Ruby on rails 如何将两个rails查询优雅地链接在一起?,ruby-on-rails,activerecord,count,find,Ruby On Rails,Activerecord,Count,Find,我有以下模型对象: #<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"> # 支持者有很多见解,支持者有很多见解 我可以通过以下方式查询数据库: 背书.查找(15).insights.count 洞察。按支持者id(15)查找所有。计数 如何将这两个查询优雅地链接在一起,以便搜索由背书15和

我有以下模型对象:

#<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">
#
支持者有很多见解,支持者有很多见解

我可以通过以下方式查询数据库:

背书.查找(15).insights.count

洞察。按支持者id(15)查找所有。计数

如何将这两个查询优雅地链接在一起,以便搜索由背书15和支持者15创建的所有见解?

试试这个

对于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

我不确定您是否希望将它们链接在一起,因为每一个都是不同的查询。如果他们之间有关系,那对我来说是有意义的。例如,如果您希望从第一次查询的结果中找到supporter_id=15的所有见解,那么如果您希望找到supporter_id=15的所有见解,那么如果您认可包含支持者的见解。

rwilliams答案是有意义的。。。这看起来像是你在重读你文章的最后一行时想要做的:)
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