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

发布于 2024-12-06 07:00:55 字数 484 浏览 0 评论 0原文

我有以下模型对象:

#<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">

其中 Endorse has_many 见解,Supporter 有很多见解。

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

<块引用>

Endorse.find(15).insights.count

Insight.find_all_by_supporter_id(15).count

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

I have the following model object:

#<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">

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

不打扰别人 2024-12-13 07:00:55
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     
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     
ι不睡觉的鱼゛ 2024-12-13 07:00:55

尝试这个

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

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
纵性 2024-12-13 07:00:55

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文