prasvin
prasvin

Reputation: 3019

Rails / Active Record has_and_belongs_to_many association - fetching a record

I have two models User and Company associated by has_and_belongs_to_many. I can fetch all users belonging to a certain company using

Company.find(id).users 

The problem I've is finding all users that DO NOT belong to a certain company. Well, I could do that using

User.all - Company.find(id).users

But, I feel there's certainly a better way to achieve this. Is there an activerecord solution to this ?

Currently, I have 8 users (id from 1 to 8). When I try,

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

I get result [7, 8] which is as expected. When I place != in the above query, the results are not what I want, i.e. array of 1 to 6.

Need help. Thanks.

Upvotes: 2

Views: 263

Answers (1)

Justin Kittridge
Justin Kittridge

Reputation: 31

The easiest way might be with a class method... something like:

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

Then in your code:

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

YMMV; I've done similar things in the past, but the above code is untested.

Also, if this is a common query pattern, you would probably be better served by the extensions to ARel provided in MetaWhere and its companion MetaSearch. N.B. These are replaced by new gems by the same author in Rails 3.1

Hope this helps.

Upvotes: 2

Related Questions