Forum: Ruby on Rails select_tag help

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.
Debcfd8f3f533800e2711c704825f9c0?d=identicon&s=25 Scott Kulik (kuliksco)
on 2009-03-21 14:44
I'm trying to create a select tag for a search form that defaults to
-->Fake when nothing has been selected.  I have tried using the
following:

<%= select_tag(:fake, options_for_select({"-->Fake" => "", "Yes" => 1,
"No" => 0}, params[:fake].to_i)) %>

for some reason though, No is selected initially when no GET parameter
is passed and the options are not in the correct order.  they show up
like the following:

No
-->Fake
Yes

Can you someone help me out with this?  thanks!
81b61875e41eaa58887543635d556fca?d=identicon&s=25 Frederick Cheung (Guest)
on 2009-03-21 15:30
(Received via mailing list)
On Mar 21, 1:44 pm, Scott Kulik <rails-mailing-l...@andreas-s.net>
wrote:
>
Hashes are not ordered  in ruby 1.8 - if you want an ordering use an
array (eg  [['Yes', 1], ['No',0]]).
For an option to be preselected it's value (the second bit) must be
equal to the last argument to select_tag (equal in the sense of ==, so
in particular '1' != 1)

In your case you are passing params[:fake].to_i. If there are no
parameters then params[:fake] is nil, and nil.to_i == 0 so rails
selects the option with value 0.

Fred
Debcfd8f3f533800e2711c704825f9c0?d=identicon&s=25 Scott Kulik (kuliksco)
on 2009-03-21 17:08
Frederick Cheung wrote:
> On Mar 21, 1:44�pm, Scott Kulik <rails-mailing-l...@andreas-s.net>
> wrote:
>>
> Hashes are not ordered  in ruby 1.8 - if you want an ordering use an
> array (eg  [['Yes', 1], ['No',0]]).
> For an option to be preselected it's value (the second bit) must be
> equal to the last argument to select_tag (equal in the sense of ==, so
> in particular '1' != 1)
>
> In your case you are passing params[:fake].to_i. If there are no
> parameters then params[:fake] is nil, and nil.to_i == 0 so rails
> selects the option with value 0.
>
> Fred

thanks fred.  changing to an array fixed the ordering problems.
for the select statement, i changed the initial value for -->Fake to -1

select_tag(:fake,
options_for_select([["-->Fake","-1"],["Yes",1],["No",0]],
params[:fake].to_i))

everything works great!
This topic is locked and can not be replied to.