Timeをテキストフィールドで扱う方法

Railscasts - Time in Text Field
より

書き方

view こんな感じで扱う。

<%= f.text_field :hoge_at_string %>


model ではparse時に発生したエラーをインスタンス変数を用いてハンドリングする。

def hoge_at_string
  due_at.to_s(:db)
end

def hoge_at_string=(due_at_str)
  self.due_at = Time.parse(due_at_str)
rescue ArgumentError
  @due_at_invalid = true
end

def validate
  errors.add(:due_at, "is invalid") if @due_at_invalid
end