一般编辑时间时我们使用datetime_select:
[code]
<%= f.datetime_select :due_at %>
[/code]
如果我们希望用text_field来编辑时间,可以这样做:
[code]
<% f.text_field :due_at_string %>
[/code]
修改Task类:
[code]
class Task < ActiveRecord::Base
def due_at_string
@due_at_string || due_at.to_s(:db)
end
def due_at_string=(due_at_str)
@due_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
[/code]
parse时间我们还可以用chronic这个ruby插件,可以parse "tomorrow"等fancy的东西
[code]
<%= f.datetime_select :due_at %>
[/code]
如果我们希望用text_field来编辑时间,可以这样做:
[code]
<% f.text_field :due_at_string %>
[/code]
修改Task类:
[code]
class Task < ActiveRecord::Base
def due_at_string
@due_at_string || due_at.to_s(:db)
end
def due_at_string=(due_at_str)
@due_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
[/code]
parse时间我们还可以用chronic这个ruby插件,可以parse "tomorrow"等fancy的东西