Nate
Nate

Reputation: 530

How to find records with nil associations in Rails

These are obviously not my actual Models but they serve as an example. I have the following class definitions.

class Movie < ActiveRecord::Base
    has_one :opening
    has_one :opening_info, through: :opening
end

class Opening < ActiveRecord::Base
    belongs_to :movie
    has_one :opening_info
end

class OpeningInfo < ActiveRecord::Base
    belongs_to :opening
    # OpeningInfo has a opening_date attribute in the DB
end

I want to find all movies that have a valid Opening, a valid OpeningInfo through that Opening, and that OpeningInfo has a opening_date that is not nil. By valid I mean it exists. I have tried several expressions using joins and includes but it complains of illegal sql statements. Any ideas?

Upvotes: 1

Views: 277

Answers (1)

IngoAlbers
IngoAlbers

Reputation: 5802

This should probably work, when opening_infos is the table name:

Movie.joins(:opening_info).where.not(opening_infos: { opening_date: nil })

Upvotes: 2

Related Questions