Rails habtm 并在没有关联的情况下查找记录 [英] Rails habtm and finding record with no association

查看:33
本文介绍了Rails habtm 并在没有关联的情况下查找记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 2 个模型:

class User < ActiveRecord::Base
    has_and_belongs_to_many :groups
end

class Group < ActiveRecord::Base
    has_and_belongs_to_many :users
end

我想创建一个范围(这很重要 - 对于效率和链接范围的能力)返回不属于任何组的用户.经过多次尝试,我没有做一个方法而不是作用域,这使得 collectUser.all 上很丑陋而且......不对.

I want to make a scope (that's important - for efficiency and for ability to chain scopes) that returns Users that doesn't belong to ANY Groups. After many tries, I failed in doing a method instead of scope, which makes collect on User.all which is ugly and.. not right.

有什么帮助吗?

也许对于第二个问题:我设法创建了一个范围,该范围返回属于任何给定组的用户(以 id 数组的形式给出).

And maybe for 2nd question: I managed to make a scope that returns Users who belongs to any of given groups (given as an array of id's).

scope :in_groups, lambda { |g|
        {
          :joins      => :groups,
          :conditions => {:groups => {:id => g}},
          :select     => "DISTINCT `users`.*" # kill duplicates
        }
      }

它可以更好/更漂亮吗?(使用 Rails 3.0.9)

Can it be better/prettier? (Using Rails 3.0.9)

推荐答案

您的隐式连接表会根据命名约定命名为 groups_users.在您的数据库中确认一次.假设是:

Your implicit join table would have been named groups_users based on naming conventions. Confirm it once in your db. Assuming it is:

在较新的 Rails 版本中:

In newer Rails version:

scope :not_in_any_group, -> {
    joins("LEFT JOIN groups_users ON users.id = groups_users.user_id")
    .where("groups_users.user_id IS NULL")
}

对于较旧的 Rails 版本:

For older Rails versions:

scope :not_in_any_group, {
    :joins      => "LEFT JOIN groups_users ON users.id = groups_users.user_id",
    :conditions => "groups_users.user_id IS NULL",
    :select     => "DISTINCT users.*"
}

这篇关于Rails habtm 并在没有关联的情况下查找记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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