Creating a Helper for Menu Options

A helper is simply a method that produces useful results in a controller or view. Here we create a helper that delivers options for a drop-down menu (SELECT control in an HTML form).

This helper assumes that we have a model that uniquely lists the names and respective ids. It allows the menu to display the names and returns the respective id of the selected name.

Helper declaration

The following code defines the helper in a controller. This code should follow method definitions for handling requests.

  protected
	
  def student_select_options
    Student.find(:all).collect {|s| [ s.name, s.id ] }
  end

  # this command makes the helper available in the views
  helper_method :student_select_options

Using the Helper in a Form

The helper can then be used in a form to create a drop-down menu:

  <%= f.label :student_id %><br />
  <%= f.select :student_id, student_select_options %>

Helpers are an example of abstraction. The details of producing the needed results are placed in a method definition. Later, we can use the helper without worrying about the details of how the results are obtained.