1

I have 2 tables in database: cars and domains. One car can have many domains and one domain can have many cars.

In my project three models:

class Car < ActiveRecord::Base

  has_many :cars_domains
  has_many :domains, :through => :cars_domains

...

class Domain < ActiveRecord::Base

    has_many :cars_domains
    has_many :cars, :through => :cars_domains
...

class CarsDomain < ActiveRecord::Base
  belongs_to :car
  belongs_to :domain
end

I want to see cars which without domain:

@cars = Car.find(:all, :conditions => ['id not in(select car_id from cars_domains where domain_id = ?)', params[:domain_id]])

It's work, but I think it's very difficult. Maybe possible to do it more simple?

1
  • 1
    I'd use a left join rather than a subquery Commented Aug 29, 2012 at 13:01

1 Answer 1

1

Tried this in a quick app I created:

domain = Domain.find(params[:domain_id])
Car.includes(:cars_domain).where('cars_domain.domain_id <> ?', domain.id)

The reason I query the domain object is because I'm always weary about passing a value from the request headers as a query parameter in SQL.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.