Store time interval in PostgreSQL from Rails

断了今生、忘了曾经 提交于 2020-01-02 07:39:09

问题


I need to store time inverval in PosgreSQL. Data will be put from Ruby on Rails.

Say, PizzaHut accepts orders from 9:00 to 18:00.

I've created following migration:

class AddOrderTimeAndDeliveryTimeToMerchants < ActiveRecord::Migration
  def self.up
    add_column :merchants, :order_time, :interval
  end

I've read the documentation, and have following code now:

Merchant.create( :delivery_time => "9:00 18:00" )

When i execute it, i get following error message:

PGError: ERROR:  invalid input syntax for type interval: "9:00 18:00"

How to do it correctly ?


回答1:


I don't think an interval is really what you want for that. An interval represents a timespan without any specific end points; for example, you add an interval to an existing time to get another time. You would be better off with two distinct times:

add_column :merchants, :order_from, :time, :null => false
add_column :merchants, :order_to,   :time, :null => false

Then, if for some reason you need to know how many hours they're open for delivery, you can construct an interval by subtracting :order_from from :order_to.

If you really must use an interval, then you'll need to construct a value something like this:

:delivery_time => "interval '11 hour'"

Note how this illustrates that an interval is not a specific time range from A to B, it is just a time range of some certain length (with no specified end points).




回答2:


It's likely that you want a time without timezone here, since if Dominoes in NY opens at 9:00 local time, and Dominoes in California also opens at 9:00 local time, then a time with a timezone would not work properly.

What you likely want is one of two things. either two times a start and an end time, or a start time and an interval. I would suggest two times, but the choice is yours. Note that you can an interval from two times by subtracting one from the other.

select '09:00:00'::time - '05:00:00'::time;
 ?column? 
----------
 04:00:00


来源:https://stackoverflow.com/questions/6441775/store-time-interval-in-postgresql-from-rails

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