如何运行计算两列的总和? [英] How to run calculations on sum of two columns?
问题描述
在发票
类我的Rails应用程序,我需要找到那些过期的发票。
In the Invoice
class of my Rails application I need to find all invoices that are overdue.
我只有两个数据库列,日期
(这是一种日期时间
字段)和 days_allowed
(这是一种整数
字段)。
I have only two database columns, date
(which is a type datetime
field) and days_allowed
(which is a type integer
field).
这是我有:
class Invoice < ActiveRecord::Base
def self.overdue
where("date + days_allowed < ?", Date.today)
end
end
这是既没有引发错误,也不回来,我需要的关系,虽然。
It's neither throwing an error nor returning the relation that I need, though.
有没有更好的方式来总结两台数据库列,然后进行计算就可以了?
Is there a better way to sum two database columns and then do calculations on it?
感谢您的帮助。
推荐答案
虽然有数据库特定的SQL两轮牛车,可以做到这一点,和其他的答案都建议,我会做不同的方式...你有兴趣的属性称为date_due,但是该属性不存在。我会做到这一点。
While there are database-specific sql hackery that could do this, and other answers have suggested, I would do this a different way... You are interested in an attribute called "date_due", but that attribute doesn't exist. I'd make it.
- 添加迁移,增加了一个invoice_due_on场到表
- 在模型中添加before_save挂钩,这样的事情:
before_save :calculate_due_date
def calculate_due_date
invoice_due_on = your_other_date + days_allowed.days
end
- 在做一些事情来触发所有现有的发票,让他们保存,更新了新的领域。例如,从控制台:
Invoice.all.each do |i|
i.save
end
这个答案依赖于通过的ActiveSupport创业板的Rails给你一些最新的魔术。随着的ActiveSupport,你可以做各种日期的功能,如:
This answer relies on some date magic given to you in Rails by the ActiveSupport gem. With ActiveSupport, you can do all kinds of date math, like:
4.days.from_now
my_birthday - 7.days
等。多数民众赞成days_allowed.days方法做上述事情。
and so on. Thats what the 'days_allowed.days' method does above.
这篇关于如何运行计算两列的总和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!