views:

115

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?

The function is being invoked using observe_field:

<%= observe_field :foo, :url => { :action => :populate } %>

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

def populate
  # what goes here?
end

Thanks!

A: 

I think you've misunderstood what observe_field does. It executes some javascript when the field changes. If you could give us some more detail on what you want to do, that'd be nice.

For example, are you trying to do something like changing the values in a select depending on what you select in another field?

dvyjones
@dvyjones, I'm looking to change the values in the select using the "populate" function which is triggered using the observe_field helper method when the value of the select change. Basically I'm just trying to figure out how to put values into the select from a function defined in the controller. Eventually I'll probably expand on it to do more things, but for now I'm just trying to figure out the basics. Does this help?
Corey
Sortof. You need to add a `populate.js.erb` or `populate.js.rjs` view in your views dir. Then you need to call stuff from there. (Google RJS for more info)
dvyjones
A: 

Try something like this...

In your application_helper.rb, put the following:

$MEMBERROLE = ['Student', 'Coach', 'Staff', 'Administrator']

Then in your view, you can put the following:

 <p>
   <%= f.label :role %><br />
   <%= f.select(:role, options_for_select($MEMBERROLE.collect{|x| [x, $MEMBERROLE.index(x)]}, @member.role)) %>
 </p>

This is assuming you have a Member model that looks something like this:

  create_table "members", :force => true do |t|
    t.string "name"
    t.integer "role"
  end

That's a dead simple way of doing it. You could also have roles as a separate table, but I figured it was overkill for what you are looking for...

Sonny Parlin