导轨的habtm和调查记录,无关联 [英] Rails habtm and finding record with no association

查看:119
本文介绍了导轨的habtm和调查记录,无关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个型号:

class User < ActiveRecord::Base
    has_and_belongs_to_many :groups
end

class Group < ActiveRecord::Base
    has_and_belongs_to_many :users
end

我希望做一个的范围(这很重要 - 的效率和能力,链范围)返回一个不属于任何群用户。 多次尝试后,我没有这样做的方法,而不是范围,这使得收集 User.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
        }
      }

它可以更好/ $​​ P $ pttier? (使用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:

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.*"
}

这篇关于导轨的habtm和调查记录,无关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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