如何获取关联对象的最早和最晚日期 [英] How to get earliest and latest dates for associated objects

查看:31
本文介绍了如何获取关联对象的最早和最晚日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 Rails 4 应用程序,我有两个模型.一个叫做Project,另一个叫做Task.

I am developing an Rails 4 app and I got two models. One is called Project and the other is called Task.

Project 有很多 Tasks.Task 属于 Project.

Project has many Tasks. Task belongs to Project.

任务对象具有starts_atends_at 属性(日期时间).如何获取属于特定项目的所有关联任务的最早starts_at 和最新ends_at?

The task objects have starts_at and ends_at attributes (datetime). How can I get the earliest starts_at and latest ends_at of all the associated tasks that belongs to a specific project?

我尝试了 @project.tasks.max(:starts_at) 但它没有用(出错).

I tried @project.tasks.max(:starts_at) but it did not work (got error).

推荐答案

使用 maximum 而不是 max.

max 是数组最大值:[1,2].max == 2

http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-maximum

这篇关于如何获取关联对象的最早和最晚日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆