Ruby Rails Time.change does not work as I would expect ... I checked the docs!

I have a form containing one date element and 3 time elements. This is due to the fact that 3 time events will occur on the same date, and I do not want the user to enter this date 3 times.

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

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

but it didn’t work. Here is a simple test that I wrote that I 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 must be different, but they are the same. Does anyone know a better way to merge a Time and Date object?

+4
source share
2 answers

You need to assign it. If you go to 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 

therefore it is possible:

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

may work for you. I do not know how I feel about this solution, but it should work.

+15
source

Also note that to change the minute you use :min instead of :minute

0
source

All Articles