In my Rails app, projects can have videos. I want to create a scope for the Project to grab projects that do not have a video associated with it. How do I do this?
Here are my model associations
class Project < ActiveRecord::Base
has_one :video
end
class Video < ActiveRecord::Base
belongs_to :project
end
Just faced this right now, and this has worked for me:
Project.includes(:video).where(videos: { id: nil })
The trick is to use the singular in includes
and the plural in where
building off of messanjah's answer, the way you would turn that into a scope is the following:
class Project < ActiveRecord::Base
has_one :video
scope :videoless, -> { left_joins(:videos).where("videos.id IS NULL") }
end
class Video < ActiveRecord::Base
belongs_to :project
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With