Rails / Active Record has_and_belongs_to_many关联 - 获取记录

时间:2012-01-06 06:46:39

标签: mysql activerecord ruby-on-rails-3.1 has-and-belongs-to-many

我有两个模型User和Company由has_and_belongs_to_many关联。 我可以使用

获取属于某个公司的所有用户
Company.find(id).users 

问题是我发现所有不属于某个公司的用户。好吧,我可以用

做到这一点
User.all - Company.find(id).users

但是,我觉得有一个更好的方法来实现这一目标。是否有一个积极的记录解决方案吗?

目前,我有8个用户(id为1到8)。当我尝试时,

User.joins(:companies).where('companies.id = ?', 13).map(&:id)

我得到的结果[7,8]正如预期的那样。当我在上面的查询中放置!=时,结果不是我想要的,即1到6的数组。

需要帮助。 感谢。

1 个答案:

答案 0 :(得分:2)

最简单的方法可能是使用类方法......类似于:

class User

  has_and_belongs_to_many :companies

  class << self

    def exclude_company(company)
      User.scoped.reject! {|u| u.companies.include? company}
    end
  end
end

然后在你的代码中:

@company = Company.find(company_id)
@users = User.exclude_company(@company)

因人而异;我过去做过类似的事情,但上面的代码没有经过测试。

此外,如果这是一种常见的查询模式,MetaWhere及其随附的MetaSearch中提供的ARel扩展可能会更好。注: Rails 3.1中的同一作者用新宝石取代了这些宝石

希望这有帮助。

相关问题