1

I have these models

class Car < ApplicationRecord
  has_many :car_locations ,:dependent=>:destroy
  has_many :rides,:dependent=>:destroy
end

class CarLocation < ApplicationRecord
  belongs_to :car
end

class Ride < ApplicationRecord
  belongs_to :car
end

There is a status attribute in Ride Model of boolean type.

Now I want those CarLocations whose car rides status is false or don't have any car ride with in minimum complexity.

1 Answer 1

2

I want those Car Locations whose car rides status is false

CarLocation.joins(car: :rides).where(rides: { status: false })

or don't have any car ride

CarLocation.includes(car: :rides)
           .where(rides: { id: nil })
           .references(:rides)

Combining both together:

CarLocation.includes(car: :rides)
           .where('rides.status = false OR rides.id IS NULL')
           .references(:rides)
Sign up to request clarification or add additional context in comments.

10 Comments

This cause error : > ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: missing FROM-clause entry for table "rides" LINE 1: ...ECT "car_locations".* FROM "car_locations" WHERE (rides.stat...
@JaiKumarRajput according to your description in OP this is impossible. I mean, this should work with the set up you've shown
if I replace includes with joins then this works perfect. but using includes... facing error. Please correct me if I'm doing somthing wrong
CarLocation.includes(car: :rides).where('rides.status = false OR rides.id IS NULL').references(:rides) - does this work ?
@dp7 super nice catch! Thanks! I'm on Rails5 and did not have to use references (worked without it)
|

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.