views:

623

answers:

1

I have a form that contains one date element and 3 time elements. This is because 3 time events will occur on one date, and I don't want the user to have to input that date 3 times.

On the server side, I would like to combine the one date with the 3 times to get 3 datetime objects. I was thinking I could just do something like:

time_object.change(:day => date_object.day, :month => date_object.month, :year => date_object.year)

but this has not worked. Here is a simple test I have written that I would expect to work:

  def before_validation
    logger.info("show_time = " + self.show_time.to_s)
    self.show_time.change(:year => 2012)
    self.show_time.change(:minute => 30)
    logger.info("show_time = " + self.show_time.to_s)
  end

The two print statements should be different, but they are the same. Does anyone know the best way to merge a Time and Date object?

+2  A: 

You need to assign it. If you go into script/console:

>> t = Time.now
=> Thu Apr 09 21:03:25 +1000 2009
>> t.change(:year => 2012)
=> Mon Apr 09 21:03:25 +1000 2012
>> t
=> Thu Apr 09 21:03:25 +1000 2009
>> t = t.change(:year => 2012)
=> Mon Apr 09 21:03:25 +1000 2012
>> t
=> Mon Apr 09 21:03:25 +1000 2012

so maybe:

self.show_time = self.show_time.change(:year => 2012)

could work for you. I don't know how I feel about that solution, but it should work.

railsninja