I have 2 fields that is asscociated with 1 attribute in my model. I am applying it in 2 of my attributes: start_at, and end_at. I am using Timepicker Plugin for jQuery.
I based my answer here: https://stackoverflow.com/questions/18461798/rails-4-convert-datetime-into-separate-date-and-time-fields#=
MY PROBLEM IS THAT THE DATE IS NOT PARSING PROPERLY.
Below are my codes:
Appointment model:
before_save :convert_to_datetime
attr_accessor :start_date, :start_time, :end_date, :end_time
def start_date
start_at.strftime("%d/%m/%Y") if start_at.present?
end
def start_time
start_at.strftime("%I:%M%p") if start_at.present?
end
def start_date=(date)
# Change back to datetime friendly format
@start_date = Date.parse(date).strftime("%Y-%m-%d")
end
def start_time=(time)
# Change back to datetime friendly format
@start_time = Time.parse(time).strftime("%H:%M:%S")
end
def end_date
end_at.strftime("%d/%m/%Y") if end_at.present?
end
def end_time
end_at.strftime("%I:%M%p") if end_at.present?
end
def end_date=(date)
# Change back to datetime friendly format
@end_date = Date.parse(date).strftime("%Y-%m-%d")
end
def end_time=(time)
# Change back to datetime friendly format
@end_time = Time.parse(time).strftime("%H:%M:%S")
end
def convert_to_datetime
self.start_at = DateTime.parse("#{@start_date} #{@start_time}")
self.end_at = DateTime.parse("#{@end_date} #{@end_time}")
end
Strong params:
params.require(:task).permit(:category_id, :subcategory_id, :title, :description, :pay_offer, :pay_type, :county_id, :area_id, appointments_attributes: [:id, :start_date, :start_time, :end_date, :end_time])
If you are wondering, appointment is a nested attribute of task model.
Here is the error:
ArgumentError (invalid date):
app/models/appointment.rb:26:in `parse'
app/models/appointment.rb:26:in `start_date='
app/controllers/tasks_controller.rb:9:in `create'
Its referring to this line: @start_date = Date.parse(date).strftime("%Y-%m-%d")
LOG:
"appointments_attributes"=>{"0"=>{"start_date"=>"3/20/2015",
"start_time"=>"12:30 AM",
"end_date"=>"3/21/2015",
"end_time"=>"01:30 AM"}}},
"commit"=>"Create Task"}
Please help. :(