Reputation: 789
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?
Upvotes: 1
Views: 269
Reputation: 13621
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.
Upvotes: 1