Learn by Doing wrote:
How do I create a radio_button_tag for every value of a constant
array? E.g., I have this constant array: VALID_ORIENTATIONS =
[“Straight”, “Gay”, “Bisexual”] . A user is presented with a form to
search for other users according to sexual orientation. Currently,
the form looks like this:
<%= radio_button_tag :orientation, "Straight",
params[:orientation] == 'Straight',
:id => "Straight" %>Straight
<%= radio_button_tag :orientation, "Gay",
params[:orientation] == 'Gay',
:id => "Gay" %>Gay
<%= radio_button_tag :orientation, "Bisexual",
params[:orientation] == 'Bisexual',
:id => "Bisexual" %>Bisexual
<%= radio_button_tag :orientation, "",
:id => "Any" %>Any
This is not DRY. How can I iterate through every value in the
constant array to make these radio buttons? Is partial appropriate
for this? The array has only three values.
You used the word “iterate” to describe what you want to do. Does that
ring any bells? Right! Use Array#each or render :partial, :collection.
Also: consider using the array indices, not the actual words, for the
value attributes of the buttons.
BTW, why aren’t you using Haml?
Also: the blank in the last radio button is obviously not in the
array. It’s there to allow the user to not use this search
criterion. Is there a better way for a user to unselect a radio
button without choosing any other?
No. Use a element instead (and check out collection_select).