views:

73

answers:

2

I have a Rails web application with a select box:

<%= select_tag :foo %>

I'm looking to write a function in the controller which would populate this select box with some values. What code would I need to write in order to do that?

It's fine if the values are hard coded into the function.

def populate
  # what goes here?
end
+1  A: 

Take a look at options_for_select. It builds the html for what you want to display.

  options_for_select([["Dollar", "$"], ["Kroner", "DKK"]])
    <option value="$">Dollar</option>\n<option value="DKK">Kroner</option>

  options_for_select([ "VISA", "MasterCard" ], "MasterCard")
    <option>VISA</option>\n<option selected="selected">MasterCard</option>

  options_for_select({ "Basic" => "$20", "Plus" => "$40" }, "$40")
    <option value="$20">Basic</option>\n<option value="$40" selected="selected">Plus</option>

  options_for_select([ "VISA", "MasterCard", "Discover" ], ["VISA", "Discover"])
    <option selected="selected">VISA</option>\n<option>MasterCard</option>\n<option selected="selected">Discover</option>

You can just pass the result of this function to select_tag like so:

  <%= select_tag 'company_id', options_for_select(@current_user.active_companies.map { |c| [c.name, c.id] }) %>
Jeff Paquette
thanks! how would you return the result of the options_for_select function from the function which will be calling it in the controller in order to insert it into the select box?
Corey
Edit my answer to show how to invoke.
Jeff Paquette
A: 

Doing things like populating a select are best done in a helper. If your controller is named MyController then you can have a MyHelper module in the helpers directory. Methods, etc. inside the helper will be available inside your view templates. So, you could have a populate_select method in your MyHelper and do everything there that you are wanting to do in your controller. That's more "the Rails way." Helpers are intended to handle the heavy Ruby code that your templates need so you don't have to mix it with your XHTML.

Chris
what would the code look like inside the helper? and would it be the same as if it were inside the controller?
Corey
Yes, it would be the same. The point is that you want to separate your view/presentation logic from you application/business logic. The former belongs in a helper, the latter belongs in the controller. Think of helpers as an extension of the "V" in MVC. Since select boxes and other inputs only appear in views, they should be prepared by a view helper.
Chris