#32 Time in Text Field

Although Rails does allow you to edit time attributes with text fields, it's not very flexible. In this episode you will learn how to use a virtual attribute to format the time to your liking.
<!-- tasks/_form.rhtml -->
<%= f.text_field :due_at_string %>
# models/task.rb
def due_at_string
  due_at.to_s(:db)
end

def 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

你可能感兴趣的:(F#,Rails)