|
Use of Select in Views for Displaying Arrays
By: Bruce Bahlmann - Contributing Author (your
feedback
is important to us!)
In rails development, when creating web forms, you often want to display a
list of items from an array. Rails offers multiple ways to display elements
of an array within a HTML form element (i.e. using an array to dynamically
populate the available options for a given select statement) and this article attempts to show how
each is done.
The simplest way to display elements from an array within a select HTML
form is to include the array within the select statement. This is a type of
inline statement where both the select and the array declaration are
contained within the same line. Use of this form is ideal for unique lists
of items only used in that particular view - or are used to simplify the
data entry.
<select id="post_shift" name="post[shift]">
<option value="3">11PM - 7AM</option> <option value="1" selected="selected">7AM - 3PM</option> <option value="2">3PM - 11PM</option></select>
|
 |
|
Desired HTML Form Behavior |
<%= select( "post", "shift", { "7AM - 3PM" => "1", "3PM - 11PM" => "2", "11PM - 7AM" => "3"}) %>
The disadvantage of using the inline form of displaying your array in the
very select statement, is that if you need to use that same collection of
elements (the array) elsewhere within your program, you would need to
declare it again. So, if you ever need to change the contents of the array,
you would need to remember the array is declared multiple times and change
them accordingly. To avoid this the next logical step is to declare the
array elsewhere (as a CONSTANT) and simply use that declaration within the view to populate
your select statement.
[apps/models/post.rb]
class Post < ActiveRecord::Base
CAMPUSES = { "7AM - 3PM" => "1", "3PM - 11PM" => "2", "11PM - 7AM" => "3"}
...
end
[apps/views/post/_form_posts.html.erb]
<%= select( "post", "shift", Post::CAMPUSES);
Note: The use of CAPS in declaring an array CONSTANT within the model
is a
convention that appears to be standard practice.
Can Birds-Eye.Net help you or your Company?
Receive your Birds-Eye.Net articles and white
papers hot off
the presses by adding our RSS feed to your reader.
|
|
|
(C) Copyright Birds-Eye.Net, All rights reserved.
It is against the law to reproduce this content or any portion of it in any form without the explicit written permission of Birds-Eye Network Services, LLC. Federal copyright law (17 USC 504) makes it illegal, punishable with fines up to $100,000 per violation plus attorney's fees.
|