DenicioCode
DenicioCode

Reputation: 9336

Simple Association in Rails

I have two models. A driver and a car. The driver can own many cars. A car can be owned by many drivers. Car Model has_many :drivers, through: :car_ownership. This works and everything is fine.

But I want to return all cars with drivers only, something like this:

@cars = Car.where.not(drivers: nil)

Car.first.drivers returns all a collection of Active Record Model Driver.

Upvotes: 1

Views: 29

Answers (1)

K M Rakibul Islam
K M Rakibul Islam

Reputation: 34336

I think you want something like this (assuming your car_ownerships table has a driver_id column):

Car.joins(:car_ownerships).where('car_ownerships.driver_id IS NOT NULL')

Using pure Active Record, this query would be:

Car.joins(:car_ownerships).where.not(car_ownerships: { driver_id: nil })

Upvotes: 1

Related Questions