Select_tag helper. How do I edit collection values?

Hi everyone,

I am using a collection in a select_tag to select categories (uses) for
my object (item). I have sub categories so I want some way to
distinguish between the parent and child categories in the select list.
What I have works fine but is confusing to look at because it is just a
long list in the select box.

Here is what I have:

<%= select_tag ‘item[use_ids][]’,
options_from_collection_for_select(@uses, :id, :name,
@item.uses.collect{|use| use.id}), { :multiple => true, :size => 20 } %>

Here is what it looks like:

http://robert.naranjastudio.com/select_tag.png

I want to format the values so the items in the select box look
something like:

Backpacks
-Computer Backpacks
-Outdoor & Sports
-Wheeled
Brand Name
-Cutter & Buck
-High Sierra

Kind of like that. Does anyone know how to work that magic in the
select_tag helper using a collection like I am? Is it possible to maybe
add a “-” in the value displayed for the sub uses?

Thanks in advance for your help!!

On 5 Aug 2008, at 20:16, Robert Merrill wrote:

I want to format the values so the items in the select box look
Kind of like that. Does anyone know how to work that magic in the
select_tag helper using a collection like I am? Is it possible to
maybe
add a “-” in the value displayed for the sub uses?

Have you tried using option_groups_from_collection_for_select instead
of options_from_collection_for_select?
One way of having a - added in front would be to have a method on that
model:

Fred

Thanks Fred,

I will look into it more. I think I might have a problem using
option_groups_from_collection_for_select though, it looks like if I use
it I will not be able to put items into the main categories, only child
categories. Maybe not though. So you think adding a method to the item
model that would return the name + “-” would work? How would call it?
Like this:

<%= select_tag ‘item[use_ids][]’,
options_from_collection_for_select(@uses, :id, :name_with_dash,
@item.uses.collect{|use| use.id}), { :multiple => true, :size => 20 } %>

~Robert

<%= select_tag ‘item[use_ids][]’,
options_from_collection_for_select(@uses, :id, :name_with_dash,
@item.uses.collect{|use| use.id}), { :multiple => true, :size => 20 } %>

That worked like a charm, exactly what I wanted.

Here is what my model method looks like

def name
“#{use_name}”
end

def name_with_dash

if self.parent_id != nil
  "--#{use_name}"
else
  name
end

end

Thanks again!!