One of the questions that arises in Rails development is “how do you create a date or datetime field, on a form, for an object in your model?” Prior to Rails 2.0, the scaffold would generate a set of drop-downs–for the year, the month, the day, the hour, and even the minute–for date and date-time fields, such as created_on and updated_on. As of Rails 2.0, it doesn’t do this anymore. And if you’ve checked the API, there are no form helpers for date or datetime fields.
So what do you do if you need this functionality? Say you have a blog application, and you want to expose the created_on field so that authors can “future post” articles by specifying a date in the future to publish it–like the WordPress blog platform.
Rails provides a function called date_select (or, for datetime fields, datetime_select). They takes two parameters–the model instance name, and the model field. Put them in the form_for block, like the other form helpers.
Recall that, when you create forms for objects, Rails generates HTML that follows a convention–if you have a post title, the ID of the corresponding input field will be “post[title].”
And that’s what these two functions take as parameters–so if you wanted a datetime field, you’d write:
datetime_select("post", "created_on")
If you look at the corresponding HTML that Rails generates, it creates several fields–such as post_created_on_1i, post_created_on_2i, and so on. The good news is, you don’t have to know how it works–you can just appreciate that Rails will automatically populate the field with the right values, whether you create a new object, or edit an existing one.
All thanks to the conventions Rails follows–conventions, which lie at the heart of Rails.
So whether you have a date or datetime field, use the date_select and datetime_select functions to create fields to enter and edit those fields.