首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将两个rails查询巧妙地链接在一起?

如何将两个rails查询巧妙地链接在一起?
EN

Stack Overflow用户
提问于 2011-09-22 06:25:28
回答 3查看 1.1K关注 0票数 1

我有以下模型对象:

代码语言:javascript
复制
#<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

我如何优雅地将这两个查询链接在一起,在这里我可以搜索Protection15创建的所有洞察力,以及支持者15?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-09-22 09:52:17

代码语言:javascript
复制
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     
票数 2
EN

Stack Overflow用户

发布于 2011-09-22 06:43:26

尝尝这个

对于Rails 3.0.x和可能3.1

代码语言:javascript
复制
Endorse.find(15).insights.find_all_by_supporter_id(15).count

Rails 2.3.x

代码语言:javascript
复制
Endorse.find(15).insights.find_all_by_supporter_id(15).length
票数 1
EN

Stack Overflow用户

发布于 2011-09-22 06:43:48

我不确定您是否希望将它们链接在一起,因为每个查询都是不同的查询。如果他们之间有关系,那对我来说就有意义了。例如,如果支持包含支持者的Insight。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7510429

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档