一般编辑时间时我们使用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的东西
本文介绍如何在Rails应用中使用自定义的时间字段编辑方法,通过将默认的datetime_select替换为text_field,并实现相应的解析与验证逻辑。这种方法提高了灵活性,同时保持了数据的有效性和一致性。
1669

被折叠的 条评论
为什么被折叠?



