简体   繁体   English

Rails-在控制器中调用模型方法

[英]Rails - Calling a model method in controller

Basically, I have a datetime field in my model and I want to return it as an age. 基本上,我的模型中有一个日期时间字段,我想将其作为年龄返回。 My question is, how do I make @student_age an array of ages? 我的问题是,如何使@student_age成为年龄段?

The top image is my controller. 最上面的图像是我的控制器。 The bottom image is my model method, which inputs the SQL query. 底部的图像是我的模型方法,它输入SQL查询。

在此处输入图片说明

Student.select('date_part("year", age(dob))')

I dont quite get what you want but if you want your query automatically returns an array you can do this. 我不太明白您想要什么,但是如果您希望查询自动返回一个数组,则可以执行此操作。

In rails 4 you can add pluck to return an array. 在rails 4中,您可以添加pluck返回数组。

Student.select('date_part("year",age(dob)').pluck(:date_part)

In rails 3 you can do this. 在rails 3中,您可以执行此操作。

Student.select('date_part("year",age(dob)').collect{|x| x.date_part}

Output will be like this [24, 13, 56, 34] 输出将像这样[24、13、56、34]

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

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