在Ruby on Rails中,是否有一种方法可以获取`where`方法范围之外的对象?

huangapple go评论47阅读模式
英文:

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!"})
)

huangapple
  • 本文由 发表于 2023年7月20日 21:28:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76730401.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定