How do I make a forms in Rails (part 2)?

After setting up a basic form, you probably need to fill it with some controls. Until the advent of HTML 5 (which I can’t rely on because many of my clients are still stuck with old browsers), there wasn’t really much choice with these controls.

Rails offers helpers for generating these controls, and fills some gaps in the pre-HTML 5 world by building replacement controls.

If your person had a date_of_birth field, you could use Rails’ date_select helper:

This generates three HTML selects (year, month and date) with slightly mangled names that Rails recognises when the form is submitted, rebuilding from three separate values into a single date. These selects are displayed in international format. If, like most of my clients, you want it in a more usual format, you need to do this:

Speaking of selects, if you want to allow your user to pick an option, based on a collection of models, you can use collection_select. For example, if you had a database table for storing titles (Mr, Mrs, Miss and so on), and your person model had a “belongs_to :title” association (and hence a title_id field), you can chuck one of these in your form:

This creates a select populated with your title table’s names, and when selected, the title’s ID is stored in the person’s title_id field.

Last for today’s edition, what if you want to allow your user to manage a “has_and_belong_to_many” association. Imagine you wanted to model which musical instruments your person can play. We have an instruments table, with an Instrument model and a has_and_belongs_to_many association on the person model.

We can then let users select our person’s musical capabilities like so:

So there you have it; a few time-savers there for your forms, which should save you some time when building your user-interfaces.

Next time – more complex forms.

Do you know what to do but not how it works?

Ever wanted to understand why Rails views work the way that they do? Why variables from your controllers are visible inside your views?

Sign up below to get a free 5 part email course on how Ruby on Rails view rendering works and gain a deep understanding of the Rails magic.

We will send you the course, plus the occasional update from this web-site. But no spam, we promise, and it's easy to unsubscribe