英文:
In ruby rails, is there a method to get the objects outside of a where method's scope?
问题
对于上下文,基本上我正在尝试找出哪些用户没有某篇帖子,例如:
@specified = User.joins(:post).where(post: {content: "Goodbye!"})
与我想要获取的内容(基本上只是未包括在内的每个用户):
!@specified
我尝试否定它,但显然不起作用,有解决方法吗?
英文:
For context, basically Im trying to find out which Users don't have a certain post, for example:
@specified = User.joins(:post).where(post: {content: "Goodbye!"})
vs. what I want to get (which is basically just every user that wasnt included)
!@specified
I tried negating it but it doesn't work apparantly, Is there a solution to this?
答案1
得分: 1
这会导致重复的用户,如果用户有多个帖子,并且跳过没有帖子的用户:
User.joins(:post) # 应该是 :posts 吗?
你找到了不想要的内容:
User.joins(:post).where(post: {content: "Goodbye!"})
not
只过滤掉帖子中包含 "Goodbye!" 的帖子,如果用户有其他帖子,这个用户将包含在结果中:
User.joins(:post).where.not(post: {content: "Goodbye!"})
简单的方法是否定整个条件:
User.where.not(
id: User.joins(:post).where(post: {content: "Goodbye!"})
)
英文:
This will give you duplicate users if user has more than one post and skip users without posts:
User.joins(:post) # should it be :posts?
You found what you don't want:
User.joins(:post).where(post: {content: "Goodbye!"})
not
only filters out the post that has "Goodbye!", if a user has other posts, this user will be included in the result:
User.joins(:post).where.not(post: {content: "Goodbye!"})
Easy way out is to negate the whole thing:
User.where.not(
id: User.joins(:post).where(post: {content: "Goodbye!"})
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论