group_by 相对日期范围
我有一位客户希望查看其员工的报告,该报告按员工上一职位的日期 (date_in_position
) 分组。她希望它们按以下条件分组:不到 1 年、1-3 年、3-5 年和 5 年以上。我做了一个小方法来返回可用于 group_by
方法的字符串,但只有“不到 1 年”才能正常工作。其他一切都显示超过 5 年。
def dip_range
case self.date_in_position
when 1.year.ago...Date.today
'< 1 year'
when 3.years.ago...(1.year.ago + 1)
'1-3 years'
when 5.years.ago...(3.years.ago + 1)
'3-5 years'
else
'> 5 years'
end
end
I have a client who wants to see a report of her employees grouped by the date they took their last position (date_in_position
). She wants them grouped by: Less than 1 year, 1-3 years, 3-5 years, and over 5 years. I made a little method to return a string usable for the group_by
method, but only "less than 1 year" is working correctly. Everything else shows up as over 5 years.
def dip_range
case self.date_in_position
when 1.year.ago...Date.today
'< 1 year'
when 3.years.ago...(1.year.ago + 1)
'1-3 years'
when 5.years.ago...(3.years.ago + 1)
'3-5 years'
else
'> 5 years'
end
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
另一种方法来处理它:
another way to approach it:
在 R1.8 (Time..Date) 范围中根本不起作用,此外我无论如何都会重写这段代码:
或者甚至:
In R1.8 (Time..Date) range doesn't work at all, besides I would rewrite this piece of code anyway:
Or even:
Integer#years.ago
返回一个DateTime
,它无法与您正在打开的Date
对象进行正确比较。我不太确定这是为什么,但如果你改为
case self.date_in_position.to_datetime
此代码适用于大多数情况。
另外,你的界限不正确。如果有人 1 年前的今天开始工作,他们应该显示为 1-3 年,对吗?所以:
Integer#years.ago
returns aDateTime
which isn't comparing properly to theDate
objects you are switching on. I'm not exactly sure why this is, but if you changeto
case self.date_in_position.to_datetime
this code will work for most cases.
Also, your bounds are incorrect. If someone started work 1 year ago today, they should show as 1-3 years, right? So:
我认为这就是您想要的,因为它将按优先级顺序匹配,如果您愿意,请更改语法:
I think this is what you want because it will match in order of priority, change the syntax if you like: