Rails date format in a text_field

后端 未结 14 2196
傲寒
傲寒 2020-12-13 06:05

I have a rails form that displays a date in a text_field:

<%= form.text_field :check_in_date  %>

The date is rendered as yyyy-m

14条回答
  •  不知归路
    2020-12-13 06:41

    My preferred way of handling this is with virtual attributes. There's a short RailsCast on the subject (3m), but the upshot is that virtual attributes will allow you to use a non-standard format when displaying model attributes in a form, or vice versa (i.e., saving form data to a model).

    Basically, rather than creating a form field for the check_in_date attribute, you can define a “virtual attribute” on the model:

    class Reservation
      def check_in_date_string
        check_in_date.strftime('%m-%d-%Y')
      end
    
      def check_in_date_string=(date_string)
        self.check_in_date = Date.strptime(date_string, '%m-%d-%Y')
      end
    end
    

    Now, you can create form fields that correspond to check_in_date_string rather than check_in_date:

    <%= f.text_field :check_in_date_string %>
    

    That's it! No need to explicitly specify a value option, and when this form is submitted, the model will be updated appropriately.

提交回复
热议问题