简体   繁体   English

如何创建范围以比较关联模型上日期的最后一个实例?

[英]How do I create a scope to compare the last instance of a date on an associated model?

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. 我正在使用Rails Admin,它为我提供了使用合同模型和Rails Admin配置中定义的任何作用域的合同列表的功能。 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. 我想创建一个:expired范围,该范围列出所有合同,其中合同的最后一个期间的end_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: 对于它的价值,我已经有一个current_end_date实例方法,该方法可以通过执行以下操作为我提供合同的当前结束日期:

periods.last.end_date

But I don't know how to work something like that into a scope. 但是我不知道如何将类似的东西用于示波器。

I agree with @James - it is easiest to be split into two subqueries, however I would first find all non-expired contracts: 我同意@James-最简单的方法是将其分为两个子查询,但是我首先会找到所有未到期的合同:

scope :non_expired, -> { joins(:periods).where('periods.end_date >= ?', Date.today) }
scope :expired, -> { where.not(id: non_expired.pluck(:id)) }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM