Rails/AR 查找 habtm 不包含的地方

发布于 2024-07-27 00:11:10 字数 323 浏览 6 评论 0原文

我有一个包含用户的 Rails 应用程序,以及每个用户的 HABTM 角色。

我想选择没有特定角色的用户。 我可以使用 searchlogic,但我迷路了。 我尝试过使用条件、连接和包含的组合,但我似乎无法解决它。 这有效:

User.find(:all, :conditions => ['role_id != ?', Role[:admin].id], :joins => :roles)

查找不是管理员的用户,但不会找到没有角色的用户(我也想找到)。

在我疲惫的状态下,我错过了什么简单的事情?

I have a Rails app with Users, and each user HABTM Roles.

I want to select Users without a specific role. I have searchlogic at my disposal, and I'm lost. I've tried using a combination of conditions and joins and includes and what not, but I can't seem to nail it. This works:

User.find(:all, :conditions => ['role_id != ?', Role[:admin].id], :joins => :roles)

To find users that are not admins, but doesn't not find users with no roles (which I want to find as well).

What simple thing am I missing in my tired state?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

奢华的一滴泪 2024-08-03 00:11:10

使用子查询和 NOT IN 运算符

User.find(:all,:conditions => ["id NOT IN (select user_id from roles_users where role_id = ?)", Role[:admin].id)

Use a sub-query and the NOT IN operator

User.find(:all,:conditions => ["id NOT IN (select user_id from roles_users where role_id = ?)", Role[:admin].id)
你与昨日 2024-08-03 00:11:10

怎么样:

User.find :all, :conditions => [ 'roles.id is ? or roles.id != ?', nil, Role[:admin].id ], :include => :roles

这适用于 has_many :through,似乎对于 HABTM 应该是相同的。

How about this:

User.find :all, :conditions => [ 'roles.id is ? or roles.id != ?', nil, Role[:admin].id ], :include => :roles

This works for has_many :through, seems like it should be the same for HABTM.

追我者格杀勿论 2024-08-03 00:11:10

我可以

User.all - User.find(:all, :conditions => ['role_id = ?', Role[:admin].id], :joins => :roles)

在两个查询中完成我想要的任务,这对于这个项目来说可能很好,但是如果我可以将其实现为单个查询,那就太好了。

I can do

User.all - User.find(:all, :conditions => ['role_id = ?', Role[:admin].id], :joins => :roles)

Which accomplishes what I want in two queries, which is probably fine for this project, but if I can get it to a single query it would be nice.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文