Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
  • Creating Select Boxes using form helpers in rails

    • 0
    • 1
    • 1
    • 1
    • 0
    • 0
    • 0
    • 0
    • 306
    Comment on it

    One of the most common html elements in a web page is select box. In Rails select and option tag helper method is used to display it .

    select and option tag:

    <%= select_tag(:city_id, options_for_select[[Bangalore, 1], [Dehradun, 2]]) %>
    # <select id="city_id" name="city_id">
    #<option value="1">Banglore</option>
    #<option value="2">Dehradun</option>

    In the above example in the controller we can get the chosen city id as params[:city_id].

    The select method looks like this:

    select_tag(name, option_tags = nil, options = {})

    For the above example name is :city_id , option_tags is options_for_select[[Bangalore, 1], [Dehradun, 2]]. options = {} are the optional arguments. They are :

    :multiple - When set to true we can select more than one option.
    :disabled - When set to true the select box will be disabled in the web page.
    :include_blank - When set to true an empty option will be created.
    :prompt - When a string is passed to this option it is displayed as option without any value in the web page.

    Others ways of displaying select boxes are:

    Select box for model specific form:

    select method is used in model specific form for displaying select boxes. Example:

        <%= select(:location, :city_id, [[Bangalore, 1], [Dehradun, 2]]) %>

    Please follow this tutorial Rails:Populating Select boxes with model data for details.

    Option Tags from a Collection of Arbitrary Objects:

    In the above example we have given static values of option tag , but what to do when we have dynamic collection for option tags then we will use options_from_collection_for_select


    <%= select_tag(:city_id,  options_from_collection_for_select(@city, "id", "name")) %>

 0 Comment(s)

Sign In

Sign up using

Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: