简体   繁体   English

如何从Rails的集合中获取集合?

[英]How to get a collection from a collection in Rails?

I have collection of users with posts, and I'd like to get all the posts from all of the users. 我收集了带有帖子的用户,我想从所有用户那里获取所有帖子。 Is there a way to do something like this: 有没有办法做这样的事情:

User.active.posts.unique.visible

Active and visible are both special scopes that I've written myself. 活动和可见都是我自己编写的特殊作用域。

Assuming you have user_id column in your posts table: 假设您的posts表中有user_id列:

Post.where(user_id: User.active.map(&:id)).visible

It will generate two SQL queries without any join (unless you use join in your visible scope), so it's quite efficient way. 它将生成两个没有任何联接的SQL查询(除非您在visible范围内使用联接),因此这是一种非常有效的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM