Forum: Ruby on Rails Inserting a nil value into a Select/Drop Down Menu

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Rich (Guest)
on 2006-12-22 17:17
I might have asked this before, but I don't think I got a reply.

I'm using this code to create a drop-down menu of 'cuisines':

<%= select_tag "cuisine_id",
options_from_collection_for_select(@cuisines, 'id', 'name') %>

My question is, how can I add an "All Cuisines" option to the start of
this menu, with a nil value? Or is there someway that lets you add a
similar option? It's a common thing to have in a drop-down menu so I'm
sure it's been discussed somewhere.

I'm guessing I'd probably have to code it more explicitly. Thanks!
blaix (Guest)
on 2006-12-24 00:11
(Received via mailing list)
Since options_from_collection_for_select returns a string of normal
<option> tags, you should be able to just append it to your own
<option> tag:

<%= select_tag "cuisine_id",
"<option value=''>All Cuisines</option>" +
options_from_collection_for_select(@cuisines, 'id', 'name') %>

Or make a helper that does this for you.

Justin
rich (Guest)
on 2006-12-28 00:17
blaix wrote:
> Since options_from_collection_for_select returns a string of normal
> <option> tags, you should be able to just append it to your own
> <option> tag:
>
> <%= select_tag "cuisine_id",
> "<option value=''>All Cuisines</option>" +
> options_from_collection_for_select(@cuisines, 'id', 'name') %>
>
> Or make a helper that does this for you.
>
> Justin

Thanks this works perfectly!
Lee S. (Guest)
on 2006-12-28 07:07
(Received via mailing list)
Rich,

Does this code still work if you have a form validation error?  Where
are you declaring the @cuisines object?
seth b. (Guest)
on 2006-12-28 07:51
(Received via mailing list)
The option way works, but I do it this way as well for a list of
countries
where I want USA to appear first...

@usa = Country.find(:first, :conditions => ["name = ?", usa_name])
@countries = Country.find(:all,
                              :conditions => ['country_code IS NOT NULL
AND
name <> ?', usa_name],
                              :order => 'name ASC')
@countries.insert(0, @usa)

You might want to do a similar thing in your controller, who knows.

On 12/27/06, JL Smith <removed_email_address@domain.invalid> wrote:
>
>
> Rich,
>
> Does this code still work if you have a form validation error?  Where
> are you declaring the @cuisines object?
>
>
> >
>


--
--------------------
seth at subimage interactive
-----
http://www.subimage.com
http://sublog.subimage.com
-----
http://www.getcashboard.com
http://dev.subimage.com/projects/substruct
This topic is locked and can not be replied to.