0

I have a table that needs to store epoch timestamp.

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

However, when I stored it, it becomes nil (*the open_time and the close_time)

EX:

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

You can notice that the value of open_time is gone, and the result is

#<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>

Env:

Rails 5.1.4, Ruby 2.6.5, MySQL 5.7

rj487
  • 4,476
  • 6
  • 47
  • 88

2 Answers2

0

Rails has two "special" timestamps, created_at and updated_at that Rails automatically stores and updates it properly (t.timestamps will generate those columns). Otherwise, it's not special meaning you need to set it manually.

So for example,

def open
  update(open_time: Time.current)
end

a method like this can do what you want, and you can add anything to this method so that it does other things besides updating a column.

Masafumi Okura
  • 694
  • 3
  • 12
0

I realize my question wasn't related to Rails. I shouldn't use timestamp to store epoch time.

What is the data type for unix_timestamp (MySQL)?

Instead, I should use int(11) to store it.

Back to my question. If I want to store timestamp, I should use the time object in Rails.

EX:

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
rj487
  • 4,476
  • 6
  • 47
  • 88