Is there an ActiveRecord equivalent to using a nested subquery i.e. ... where NOT IN(select...) ?

Posted by Snorkpete on Stack Overflow See other posts from Stack Overflow or by Snorkpete
Published on 2010-04-11T12:24:19Z Indexed on 2010/04/11 12:33 UTC
Read the original article Hit count: 199

I have 3 models: Category, Account, and SubAccount
The relations are:
Accounts has_many :sub_accounts
Categories has_many :sub_accounts

I wanted to get a list of all Categories that are not used by a given account. My method in the Category model currently looks like:

class Category < ActiveRecord::Base  
  def self.not_used_by(account)
      Category.find_by_sql("select * from categories where id not in(select category_id from sub_accounts where account_id = #{account.id})")
  end
end

My question is, is there a cleaner alternative than using SQL?

NB. I am currently using Rails 3(beta)

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about rails