Technical Blog about all things computer

  • Feb 28

    This article is about how to add a calendar date picker to your Ruby Rails Web page.

    There are a couple of ways developers use the selected dates, either to store as data in the database or a variable used in the program’s logic.

    I will cover both ways of doing it in this blog. There are multiple date and time picker libraries around. The one I’m using is the “Calendar Date Select” developed by Tim Herber.

    1.) First the plug-in needs to be installed in your project. Go to your project directory and run the following command:

    ruby script/plugin install

    2.) In your view load prototype and calendar date select.

    <%= javascript_include_tag :defaults %>
    <%= calendar_date_select_includes %>

    Method #1: Passing the select date in a variable

    3.) Add the following code to your view. “bday” is the variable the selected date will be stored in. @start_date_range is default value for the pickere and year_range specifies the year range:

    <div id=”calendar”>&nbsp; Birth Date &nbsp;
    <%= calendar_date_select_tag “bday”, @start_date_range, :year_range => 10.years.ago..0.years.ago  %>

    Pop Up Date Selector

    Result from the code above


    4.) In Your controller, to pick up the bday variable, put a code like this:

     if !params[:bday].nil?

    @birthdate = Date.parse(params[:bday]).to_s if !params[:bday].nil?


    Method #2. Passing the selected date into a database column:

    5.) If you would want to update your model directly this is an example.

    In your view enter the following for birthrate input. The column name is birthdate.:

          <% form_for :model do |form| %>
          <% fields_for :model do |f| %>
          <td> Select Birth Date: <%= f.calendar_date_select :birthdate, :embedded => true %> </td>
          <% end %>
          <% end %>

    Notice that I set embed  to true. This changes the date picker from a pop-up to a non-pop up date picker (See picture).

    Embeded Date Selector

    Result from the code above

    6.) To save the birthdate in your controller, simply apply the following assuming “birthdate” is the column name you are updating.

        if and

    Script will automatically determine the date type of your database table. And save the selected date.

    Method #2 allows you to take advantage of the error checking and all the goodies in the Rails framework.

    Tim’s demo site is down but this site contains a good demo:

    Hope this was helpful and happy coding!