开发者

Working with date time objects in rails model

I have two columns in my model, start_time and end_time.

The view to generate this model has a cool calendar for the date and a nifty time selector for the time, but I cant figure out how to make this more elegant. I want to be able to store both the date and time from my form in the database without all this mess, Rails has to have a better way, right?

I came up with this solution an开发者_开发百科d every time I look at it I get nauseous. Any ideas on how to make this prettier?

attr_accessor :start_time_time, :end_time_time, :start_time_date, :end_time_date

def start_time_date
  self.start_time.try(:strftime,DATE_FORMAT)
end

def end_time_date
  self.end_time.try(:strftime, DATE_FORMAT)
end

def start_time_time
  self.start_time.try(:strftime, TIME_FORMAT)
end

def end_time_time
  self.end_time.try(:strftime, TIME_FORMAT)
end

def start_time_date=(date)
  begin
    self.start_time = nil
    self.start_time = Time.zone.parse("#{Date.strptime(date, DATE_FORMAT).to_formatted_s(:db)} #{start_time_time}") unless date.blank?
  rescue
    errors.add(:start_time_date)
  end
end

def end_time_date=(date)
  begin
    self.end_time = nil
    self.end_time = Time.zone.parse("#{Date.strptime(date, DATE_FORMAT).to_formatted_s(:db)} #{end_time_time}") unless date.blank?
  rescue
    errors.add(:end_time_date)
  end
end

def start_time_time=(time)
  begin
    self.start_time = Time.zone.parse("#{Date.strptime(start_time_date, DATE_FORMAT).to_formatted_s(:db)} #{time}") unless start_time_date.blank? or time.blank?
  rescue
    errors.add(:start_time_time)
  end
end

def end_time_time=(time)
  begin  
    self.end_time = Time.zone.parse("#{Date.strptime(end_time_date, DATE_FORMAT).to_formatted_s(:db)} #{time}") unless end_time_date.blank? or time.blank?
  rescue
    errors.add(:end_time_time)
  end
end


I do the above in one go with the Timepicker addon by Trent You can manipulate DateTime objects by doing start_time.to_time and also calling the to_date instance method. You don't need to set any of the above accessors at all.

I suggest you watch this screencast by Ryan, notice how the date information from his UI picker gets saved via the #create action. When you use the Timepicker addon, you can define the time as well and your DateTime will be updated with both date and time info appropriately.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜