简体   繁体   中英

populating select box from controller function in Rails

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!

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...

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM