options_for_select and <<
By chris on May 23rd 2007 in /dev/rails | 1,027 views
It's fairly common to want to grab a bunch of unique database entries and display them as a set of form option tags. Rails has which does quite a nice job of it.
But what to do when I also want to include items not in the database, such as "all" or "none"?
RUBY:
-
<%= select_tag :activity, options_for_select( ( Activity.find( :all ).collect{ |x| [ x.name, x.id ] } ).uniq <<[ "all", 0 ] ).sort, { :onchange => "submit();" } %>
In this case I'm appending "all" onto the hash that constitutes the options.
(Note that it's probably better to have the uniq be in the SQL as DISTINCT but that's for another day.)

Mark responded on 18 Jul 2007 at 3:16 pm #
Hi,
Lets say you have a user table with a many to many relationship to Activities (its a simple many to many with no model.) So I have @user.activites that I want selected in the select_tag above… .. How would you do that?
I had…
“true” } %>
However it showed the objects in the select box…
Then I have been trying to use the collect to create an array for the selected items…
true, :size =>5} ) %>
I am a newb to Ruby and Rails itself… so any help would be appreciated
Mark responded on 18 Jul 2007 at 3:35 pm #
Hi,
Lets say you have a user table with a many to many relationship to Activities (its a simple many to many with no model.) So I have @user.activites that I want selected in the select_tag above… .. How would you do that?
I had…
“true” } %>–>
However it showed the objects in the select box…
Then I have been trying to use the collect to create an array for the selected items…
I am a newb to Ruby and Rails itself… so any help would be appreciated
Mark responded on 18 Jul 2007 at 3:37 pm #
hey dude, something funky happening when I post my ruby to you… are you sure its not running any script in your comments?
Anyway, I solved the issue…I was using companies and users… got it linked…
true, :size =>5} ) %>