Search code examples
ruby-on-railsdatetimeruby-on-rails-4jquery-ui-timepicker

2 fields, 1 model attribute, date not parsing


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. :(


Solution

  • The problem is that Ruby is expecting date in %d/%m/%Y format, and you are passing it in %m/%d/%Y (notice that day and month have changed place). Date "3/20/2015" is invalid because there is no 20th month. :)

    Instead of using just Date.parse you should use strptime which allows you to specify date format that you want to parse.

     Date.strptime(date, "%m/%d/%Y")