在我的 Rails 应用程序中,我已经定义了Kid
基于以下字段的计算模型Kids
D B。方法如下:
def flip_date
self.dob.advance(months: 10)
end
我想在我的控制器中使用它,因为我有一个定义如下的方法:
new_kids = Kid.where(discharge_date: nil).where('flip_date > ?', Date.current.advance(year: 1).beginning_of_year)
但是我不断收到以下错误:
SQLite3::SQLException: no such column: flip_date: SELECT "kids".* FROM "kids" WHERE "kids"."discharge_date" IS NULL AND (flip_date < '2017-01-01')
关于如何使这项工作有效的任何想法?感谢所有帮助!
如果你真的想使用模型方法,请看一下http://apidock.com/rails/v4.0.2/ActiveRecord/QueryMethods/select http://apidock.com/rails/v4.0.2/ActiveRecord/QueryMethods/select
对于你的情况:
new_kids = Kid.where(discharge_date: nil).select{|k| k.flip_date > Date.current.advance(year: 1).beginning_of_year}
但是 select 方法在返回最终结果之前会获取内存中的每个对象。因此,我建议使用普通的 where 子句,并考虑 dob (数据库中的一列)而不是 Flip_date 。
像这样
new_kids = Kid.where(discharge_date: nil).where('dob > ?', <date criteria>)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)