How to run calculations on sum of two columns?

别来无恙 提交于 2020-01-17 00:01:41

问题


In the Invoice class of my Rails application I need to find all invoices that are overdue.

I have only two database columns, date (which is a type datetime field) and days_allowed (which is a type integer field).

This is what I've got:

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?

Thanks for any help.


回答1:


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.

  • Add a migration that adds an invoice_due_on field to your table
  • in your model add a before_save hook, something like this:

    before_save :calculate_due_date

    def calculate_due_date
      invoice_due_on = your_other_date + days_allowed.days
    end

  • do something to trigger all the existing invoices to get them to save, updating the new field. for instance, from a console:
    Invoice.all.each do |i|
      i.save
    end

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

and so on. Thats what the 'days_allowed.days' method does above.




回答2:


This depends on what type of database adapter you're using with ActiveRecord; for example, using PostgreSQL, you can add an INTERVAL to any DATETIME (aka TIMESTAMP), which uses a pretty natural syntax. TIMESTAMP '2014-01-26' + INTERVAL '3 days' = TIMESTAMP '2014-01-29' However, SQL itself has a DATEADD() function you could certainly use. What database are you using?

And here's a PostgreSQL wiki link for more information.




回答3:


Give this a shot if you're using mysql:

def self.overdue
  where("DATE_ADD(date, INTERVAL days_allowed DAY) < ?", Date.today)
end


来源:https://stackoverflow.com/questions/21362013/how-to-run-calculations-on-sum-of-two-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!