Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

211
Views
Ruby on Rails changing date not saving to object

I'm trying to change a 'time' entry with the date entered in the 'date' entry. So if the time is "2000-01-01 10:00:00 UTC" and the date is "2021-10-10" I want the output to be "2021-10-10 10:00:00 UTC".

I almost have it working, however; when I assign the updated date back to the original object, it does not save the change. For instance, in the code below, event_time contains the proper time I want, however, assigning it to @event.time and then printing @event.time shows the change did not take place.

def create
  @event = Event.new(event_params)
  event_date = @event.date
  event_time = @event.time.change(:year => event_date.year, :month => event_date.month, :day => event_date.day)

  puts event_time              # prints 2021-10-22 06:06:00 UTC
  @event.time = event_time
  puts @event.time             # prints 2000-01-01 06:06:00 UTC

  if @event.save
    redirect_to(events_path)
  else
    render('new')
  end
end

Any suggestions? I'm new to Ruby so I'm probably missing something obvious here

Here's my schema

  create_table "events", force: :cascade do |t|
    t.date "date"
    t.string "description"
    t.boolean "isMandatory"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.string "name"
    t.time "time"
    t.string "location"
  end
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You can refer to the SO answer here

The problem is that there is no time-of-day class in Ruby or Rails. All the time classes are dates or timestamps (i.e. date plus time of day). Inside the database it will be a time (without timezone) column and it will behave properly inside the database. However, once the time gets into Ruby, ActiveRecord will add a date component because there is no plain time-of-day class available, it just happens to use 2000-01-01 as the date. Everything will be fine inside the database but you'll have to exercise a little bit of caution to ignore the date component when you're outside the database in Rails.

Use datetime column type to hold a date and time. Only use time in the migration if you don't need the date (only want to store time part).

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!