Ruby on Rails Thursday, August 22, 2013

I found a way to do it. To convert the multi-parameter attributes that are submitted in the form to a specific time zone, add a method in your controller to manually convert the params into a datetime object. I chose to add this to the controller because I did not want to affect the model behavior. You should still be able to set a date on the model and assume your date was set correctly.

def create    convert_datetimes_to_pdt("start_date")    convert_datetimes_to_pdt("end_date")    @model = MyModel.new(params[:my_model])    # ...  end    def update    convert_datetimes_to_pdt("start_date")    convert_datetimes_to_pdt("end_date")    # ...  end    def convert_datetimes_to_pdt(field)    datetime = (1..5).collect {|num| params['my_model'].delete "#{field}(#{num}i)" }    if datetime[0] and datetime[1] and datetime[2] # only if a date has been set      params['my_model'][field] = Time.find_zone!("Pacific Time (US & Canada)").local(*datetime.map(&:to_i))    end  end

Now the datetime will be adjusted to the correct time zone. However, when the user goes to edit the time, the form fields will still display the time in UTC. To fix this, we can wrap the fields in a call toTime.use_zone:

Time.use_zone("Pacific Time (US & Canada)") do    f.datetime_select :start_date  end

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/ed3b8591-9e0a-4fa9-b761-e3d5619657a1%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

No comments:

Post a Comment