2个字段,1个模型属性,日期不解析

时间:2015-03-05 10:35:20

标签: ruby-on-rails datetime ruby-on-rails-4 jquery-ui-timepicker

我有2个字段与我的模型中的1个属性相关联。我在我的两个属性中应用它:start_at和end_at。我正在为jQuery使用Timepicker插件。

我的答案基于:https://stackoverflow.com/questions/18461798/rails-4-convert-datetime-into-separate-date-and-time-fields#=

我的问题是这个日期不合适。

以下是我的代码:

约会模式:

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

强烈的参数:

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])

如果您想知道,约会是任务模型的嵌套属性。

这是错误:

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'

它指的是这一行:@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"}

请帮忙。 :(

1 个答案:

答案 0 :(得分:0)

问题是Ruby期望以%d /%m /%Y格式表示日期,并且您将它传递给%m /%d /%Y(注意日期和月份已更改位置)。日期“3/20/2015”无效,因为没有第20个月。 :)

您应该使用strptime而不是仅使用Date.parse,它允许您指定要解析的日期格式。

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