Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails scope: association is nil

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
like image 374
scientiffic Avatar asked Sep 13 '25 10:09

scientiffic


2 Answers

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

like image 61
Pedro Adame Vergara Avatar answered Sep 15 '25 01:09

Pedro Adame Vergara


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
like image 37
ian root Avatar answered Sep 15 '25 01:09

ian root