Reputation: 134
Assume I have a Contract model that has many Periods (to measure the duration of the contract and any renewal periods). Each Period in a contract has an end_date. I'm using Rails Admin and it gives me the ability list Contracts using any scopes that I've defined in the Contract model and the Rails Admin config. I'd like to create an :expired scope that lists all Contracts where the end_date of the last Period for the Contract is prior to today's date. Simply put, I want a scope that lists only the expired Contracts.
I tried this:
scope :expired, -> { joins(:periods).where('periods.end_date < ?', Date.today) }
This doesn't work because it gives false positives showing a Contract as expired if any of its Periods are expired, not just the last one.
For what it's worth, I already have a current_end_date instance method that can give me the current end date of a contract by essentially doing:
periods.last.end_date
But I don't know how to work something like that into a scope.
Upvotes: 0
Views: 112
Reputation: 44715
I agree with @James - it is easiest to be split into two subqueries, however I would first find all non-expired contracts:
scope :non_expired, -> { joins(:periods).where('periods.end_date >= ?', Date.today) }
scope :expired, -> { where.not(id: non_expired.pluck(:id)) }
Upvotes: 1