Arif
Arif

Reputation: 1399

Rails: Update only hour and minute of datetime field

There is a field start_time of type datetime in processes table. The initial value is set to Time.zone.now. After that the user is not allowed to change the date, only hour and minute of that start_time field is allowed to change.

So, an edit form is provided to the user that shows only hour:minute like "22:43" but when the form is submitted the field value is changed to current date and time. In the controller I've used the standard rails statement to update the values:

@process = Process.find(params[:id])
@process.update(process_params) 

In the params I get the start_time as "20:40"

Also tried the change method but it not saving the changes instead it rollbacks.

hour_minute = params[:process][:start_time].split(":")
@process.start_time.change({hour: hour_minute[0], min: hour_minute[1]})

I want to update only hour and minute of the field date should remain the same.

Upvotes: 1

Views: 2138

Answers (1)

Hardik Upadhyay
Hardik Upadhyay

Reputation: 2659

change method return changed time or date but didn't update active record it self.

you can do this for update.

hour_minute = params[:process][:start_time].split(":")
@process.update(start_time: @process.start_time.change(hour: hour_minute[0], min: hour_minute[1]))

Hope, this will help you.

Upvotes: 2

Related Questions