Rails:How to create a time column with timezone on postgres

丶灬走出姿态 提交于 2019-12-03 11:20:46

That migration do exactly what you want

class CreatePeppers < ActiveRecord::Migration
  def change
    create_table :peppers do |t|
      t.column :runs, 'timestamp with time zone'
      t.column :stops, 'time with time zone'
    end
  end
end

Types are for your choice. You can write here any type, that postgresql supports. But there may be problems with conversion to types, that rails can understand.

You seem to be confused about two separate things here - both common mistakes, almost everyone makes at least one of them.

Firstly "UTC format with timezone information" isn't specifying a time. It's specifying time AND place.

Secondly PostgreSQL's "timestamp with time zone" doesn't in fact store a time zone. It stores a UTC timestamp but it accepts a time zone. A better choice of name would be something like "absolute time". You can compare two of these values directly.

A timestamp without time zone doesn't actually give you a time unless you also have a place. You can't compare two of these unless you know which timezone each is in.

It sounds like what you want is a timestamp without time zone and a separate timezone. That way you can say "2pm on Tuesday, London Time".

Not sure this is what your want, but this works for me:

add_column :table, :from_time, :timetz
add_column :table, :to_time, :timetz

But rails seems cannot to recognize timetz type, it will be treated as String. To work around this, i register timetz as time.

ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.class_eval do
  def initialize_type_map_with_postgres_oids mapping
    initialize_type_map_without_postgres_oids mapping
    register_class_with_limit mapping, 'timetz',
                              ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::OID::Time
  end

  alias_method_chain :initialize_type_map, :postgres_oids
end

BTW, my environment is rails-4.2

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