rails where() sql 查询数组 [英] rails where() sql query on array
问题描述
我会尽量解释清楚.我对用户帖子有疑问:
I'll explain this as best as possible. I have a query on user posts:
@selected_posts = Posts.where(:category => "Baseball")
我想写以下声明.这里是伪术语:
I would like to write the following statement. Here it is in pseudo terms:
User.where(用户在@selected_posts 中有一个帖子
)
请记住,我有一个多对多的关系设置,所以 post.user
是可用的.
Keep in mind that I have a many to many relationship setup so post.user
is usable.
有什么想法吗?
/编辑
@posts_matches = User.includes(@selected_posts).map{ |user|
[user.company_name, user.posts.count, user.username]
}.sort
基本上,我需要上述内容才能工作,以便它使用在 selected_posts 中发布帖子的用户,而不是我们数据库中的每个用户.
Basically, I need the above to work so that it uses the users that HAVE posts in selected_posts and not EVERY user we have in our database.
推荐答案
只需使用以下内容:
User.find(@selected_posts.map(&:user_id).uniq)
这从所有选定的帖子中获取用户 ID,将它们转换为一个数组,并删除所有重复项.将数组传递给用户只会找到具有匹配 ID 的所有用户.问题解决了.
This takes the user ids from all the selected posts, turns them into an array, and removes any duplicates. Passing an array to user will just find all the users with matching ids. Problem solved.
要将其与您在问题中显示的内容结合起来,您可以这样写:
To combine this with what you showed in your question, you could write:
@posts_matches = User.find(@selected_posts.map(&:user_id).uniq).map{ |user|
[user.company_name, user.posts.size, user.username]
}
使用 size
来计算关系而不是 count
因为 Rails 缓存了 size 方法并且自动不会多次查找它.这对性能更好.
Use size
to count a relation instead of count
because Rails caches the size method and automatically won't look it up more than once. This is better for performance.
不确定您在查询结束时尝试使用 Array#sort 完成什么,但您始终可以执行以下操作:
Not sure what you were trying to accomplish with Array#sort at the end of your query, but you could always do something like:
@users_with_posts_in_selected = User.find(@selected_posts.map(&:user_id).uniq).order('username DESC')
这篇关于rails where() sql 查询数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!