Rails 3范围-查找不在特定组中的用户 [英] Rails 3 Scope - Find users not in a specific group

查看:81
本文介绍了Rails 3范围-查找不在特定组中的用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的问题(有点简化):

Here is my problem (a bit simplified) :

我有以下型号:

class User
has_many :group_users
has_many :groups, through: :group_users


class Group
has_many :group_users
has_many :users, through: :group_users


class GroupUser
belongs_to :group
belongs_to :user
scope :belonging_to_group ->(group) {where(group_id = group.id)}

我想对不在一个特定组中的用户进行范围划分,例如以蔬菜为例,类似这样的事情开始:

I would like to scope users that are not in one specific group, let's say veggies for examples, something that would begin like this :

scope :not_in_group, ->(group)

我尝试过具有这样的子句的东西:

I've tried stuffs with having clauses like that:

scope :not_in_group, ->(group) {joins(:group_users).merge(::GroupUser.belonging_to_group(group)).group(:title).having('count(group_users.user_id) = 0')

但似乎没有任何作用

编辑:现在还有另一个问题,如果您要通过其他类的类方法调用作用域,则可能要检查一下:Rails-使用其他类方法中的类方法具有第二类的一个属性

EDIT : I've got another problem now, you may want to check this if you're calling your scope from an other class' class method : Rails - Use a class method from a another class method with one attribute of the second class

推荐答案

EDIT :我意识到如果用户有2个组,则效果不佳,因为他在两个组中看起来都不一样.我相信MySQL找到了另一个具有用户ID和另一个group_id的group_users.

EDIT : I realised that it was not working fine if a user had 2 groups, as he would appear as not in both. I believe that MySQL found an other group_users with the user's id and the other group_id.

所以我改成了这个,这似乎可行:

So I changed to this, which seems to work :

scope :not_in_group, ->(group){
  in_group = User.joins(:group_users).where("group_users.group_id = ?", group.id)
  where(arel_table[:id].not_in in_group.map(&:id))
}

两次但有效.

以前的解决方案:仅在您的用户有一个组时有效.

Previous solution : only works if your user has one group.

最后,我找到了解决方案,我必须按照@Himesh的建议,在joins()where()中传递原始SQL.非常感谢您和@ lightswitch05的帮助.

Finally I found a solution, I had to pass raw SQL in joins() and where() as @Himesh suggested me to do. Thanks a lot to you and @lightswitch05 for your help.

您的两个建议都没有选择没有任何用户的用户,这是一个可行的解决方案:

Both of your propositions did not select the users without any group, here is a solution that works :

  def not_in_group(group)
    joins('LEFT JOIN group_users ON group_users.user_id = users.id').where("group_users.group_id != ? OR group_users.group_id is null", group.id)
  end

发现那里有一些人:路轨3 ActiveRecord where子句,其中设置了id或为空

这篇关于Rails 3范围-查找不在特定组中的用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆