【问题标题】:How to store epoch timestamp in Rails?如何在 Rails 中存储纪元时间戳?
【发布时间】:2020-08-29 02:27:09
【问题描述】:

我有一个需要存储纪元时间戳的表。

class CreateKlines < ActiveRecord::Migration[5.1]
  def change
    create_table :klines do |t|
      t.string :symbol
      t.timestamp :open_time
      t.timestamp :close_time

      t.timestamps
    end
end

但是,当我存储它时,它变成了nil (*open_timeclose_time

前:

Kline.create(open_time: Time.now.to_i)
   (0.3ms)  BEGIN
  SQL (1.5ms)  INSERT INTO `klines` (`created_at`, `updated_at`) VALUES ('2020-05-14 01:45:22', '2020-05-14 01:45:22')
   (3.8ms)  COMMIT

你可以注意到open_time的值没有了,结果是

#<Kline:0x00007f9f68c87788
 id: 600,
 symbol: nil,
 open_time: nil,
 close_time: nil,
 created_at: Thu, 14 May 2020 01:45:22 UTC +00:00,
 updated_at: Thu, 14 May 2020 01:45:22 UTC +00:00>

环境:

导轨 5.1.4, 红宝石 2.6.5, MySQL 5.7

【问题讨论】:

    标签: ruby-on-rails ruby timestamp epoch


    【解决方案1】:

    Rails 有两个“特殊”时间戳,created_atupdated_at,Rails 会自动存储并正确更新它们(t.timestamps 将生成这些列)。否则没有特殊意义需要手动设置。

    例如,

    def open
      update(open_time: Time.current)
    end
    

    这样的方法可以做你想做的事,你可以向这个方法添加任何东西,这样它就可以做除了更新列之外的其他事情。

    【讨论】:

    • 虽然准确,但如果您查看他们的示例,他们已经在这样做(通过create,而不是update
    • 是的,我想知道为什么我做不好。还是我应该切换到int
    【解决方案2】:

    我意识到我的问题与 Rails 无关。我不应该使用timestamp 来存储纪元时间。

    What is the data type for unix_timestamp (MySQL)?

    相反,我应该使用int(11) 来存储它。

    回到我的问题。如果我想存储timestamp,我应该在Rails 中使用time 对象。

    前:

    Kline.create(open_time: Time.now)
    (1.0ms)  BEGIN
      SQL (1.4ms)  INSERT INTO `klines` (`open_time`, `created_at`, `updated_at`) VALUES ('2020-05-14 01:49:15', '2020-05-14 01:49:15', '2020-05-14 01:49:15')
       (1.2ms)  COMMIT
    

    【讨论】:

      猜你喜欢
      • 2022-12-16
      • 2021-05-10
      • 2022-01-13
      • 2020-02-18
      • 2012-03-10
      • 1970-01-01
      • 1970-01-01
      • 2013-10-05
      • 2020-06-24
      相关资源
      最近更新 更多