rails where()sql查询数组

我会尽可能地解释这个。 我对用户post有疑问:

@selected_posts = Posts.where(:category => "Baseball")

我想写下面的陈述。 这是伪术语:

User.where(user has a post in @selected_posts

请记住,我有多对多关系设置,因此post.user可用。

有任何想法吗?

/编辑

 @posts_matches = User.includes(@selected_posts).map{ |user| [user.company_name, user.posts.count, user.username] }.sort 

基本上,我需要上面的工作,以便它使用在selected_posts中发布post的用户,而不是我们在数据库中的每个用户。

只需使用以下内容:

 User.find(@selected_posts.map(&:user_id).uniq) 

这将从所有选定的post中获取用户ID,将它们转换为数组,并删除任何重复项。 将数组传递给用户只会找到具有匹配ID的所有用户。 问题解决了。

要将此与您在问题中显示的内容相结合,您可以写道:

 @posts_matches = User.find(@selected_posts.map(&:user_id).uniq).map{ |user| [user.company_name, user.posts.size, user.username] } 

使用size来计算关系而不是count因为Rails缓存大小方法并且自动不会多次查找它。 这对性能更好。

不确定在查询结束时使用Array#sort尝试完成的任务,但您可以始终执行以下操作:

 @users_with_posts_in_selected = User.find(@selected_posts.map(&:user_id).uniq).order('username DESC') 

试试这个:

 user.posts.where("posts.category = ?", "Baseball") 

编辑1:

 user.posts.where("posts.id IN (?)", @selected_posts) 

编辑2:

 User.select("users.company_name, count(posts.id) userpost_count, user.username"). joins(:posts). where("posts.id IN (?)", @selected_posts). order("users.company_name, userpost_count, user.username") 

我不明白你的问题,但你可以将数组传递给where方法,如下所示:

 where(:id => @selected_posts.map(&:id)) 

它将创建一个像WHERE id IN (1,2,3,4)的SQL查询

根据您的关联,您选择的post已经拥有用户:

 @selected_posts = Posts.where("posts.category =?", "Baseball") @users = @selected_posts.collect(&:user); 

您可能希望从@users中删除重复的用户。