Сохранить только время в рельсах


April 2019


220 раз


У меня есть два поля времени в таблице , т.е. start_time and end_time. Когда я исполняю MyModel.save(start_time: '12:34'), оно сохраняется с добавлением date(Sat, 01 Jan 2000 07:25:00 UTC +00:00). Я хочу сохранить только время. я используюRails5

3 ответы


When we execute, a = MyModel.save(start_time: '12:34'), it saves only time in the database. But when we display the value in the console(a.start_time), we gets time with date. So we have to retrieve time from it by the following:


Data gets correctly saved in the database


Rails will always append date with time even its type is "time". You can achieve storing only time using sql query. But i would suggest you to use one of the following options:

1)store time in column of type fixnum or decimal in 24hrs format like "22.44"

2) Store number of seconds in column of type integer & then write a helper method to confirm it into time.

3)Use column type :time and ignore the date whole querying.


Your start_time and end_time column might be of DateTime data type. instead, try using time only field

  • Date:
    • Stores only a date (year, month, day)
  • Time:
    • Stores only a time (hours, minutes, seconds)
  • DateTime:
    • Stores both date and time
  • Timestamp
    • Stores both date and time