roshiend
roshiend

Reputation: 574

ruby rails Database time

I have created a model with arrival_time as a time

create_table :trains do |t|
  t.time :arrival_time

and I'm feeding data through a Admin panel

form do |f|
  f.inputs " Journey start from " do
  f.collection_select :start_station_id, Station.all, :id, :name, {prompt:"Select start Station"}   
  f.input :arrival_time
  f.input :departure_time
end  

However, inputs for time column in database saving with a date database view. how do I prevent saving time with date?.

All I need is time on time column

Thank You

Upvotes: 2

Views: 2323

Answers (2)

worrawut
worrawut

Reputation: 1068

I guess that you used SQLite as database. If it was a case, even if you specify t.time :arrival_time in a migration file, SQLite will parse input time and store it in column arrival_time in format of YYYY-MM-DD HH:MM:SS.SSS.

According to Date and Time Datatype of SQLite, it will only store dates and time as TEXT, REAL or INTEGER value. Therefore, when you try to keep 14:15 for arrival_time column SQLite will store something like 2000-01-01 14:15:00 instead.

My preference is to store the arrival_time as string. In case I need to display the arrival_time I can use Time.parse to convert it the Time for today or another day I want.

arrival_time = "14:15"
today = Time.now
# => 2019-04-26 22:14:08 +0700
Time.parse(arrival_time)
# => 2019-04-26 14:15:00 +0700

specific_date = DateTime.new(2017, 03, 06)
Time.parse(arrival_time, specific_date)
# => 2017-03-06 14:15:00 +0700

Refer to Time.parse

Upvotes: 0

Gurmukh Singh
Gurmukh Singh

Reputation: 2017

Use :date type instead of :time

:date : Stores only a date (year, month, day)

:time : Stores only a time (hours, minutes, seconds)

For example:

create_table :trains do |t|
  t.date :arrival_time

Upvotes: 1

Related Questions