Ruby Select list and ‘selected=”” ‘ syntax

Wow, it’s been a long time. Guess I’m a bad blogger! I’ve been absorbed in learning Ruby on Rails and also gained a couple new clients who have kept me very busy.

In one of my ‘learning’ RoR projects, I needed a Select list, which was easy enough to accomplish. However I also needed to have a specific option selected based on a database entry. I had such a hard time figuring this out for some reason!! RoR documentation is still slim, unfortunately. It can be difficult to find answers to specific issues. However, one would think it would be easier to find information on a plain old Select list. Whatever….

My original code was as follows:

f.collection_select(:venues_id, @venues_list, :id, :name)

This worked great for just showing the list options. But, it didn’t pre-select the venue name being passed in from the db. I then tried:

f.collection_select(:venues_id, @venues_list, :id, :name, {:selected => @show.venues_id} )

Also to no avail.

Finally got it to work by updating my code as follows:

f.select(:venues_id, Venues.find(:all, :order => "name").collect {|v| [v.name, v.id]}, options = {:selected => @show.venues_id})

Notice I changed the form method to ‘select’ rather than ‘collection_select’. I found this code on another website. The ‘find.collect’ method makes no sense to me, and I’m even a bit foggy on the parameters that follow it. But it does work. And the collect method does have to be there (I tested it without, with horrible results).

I now have the full selection list that I wanted with the desired option selected. Woo-hoo!

Leave a Reply

Your email address will not be published.