简体   繁体   中英

Drop down select ruby rails

Here's my code for a form that contains a drop down list -

<div class="field">
<%= f.label :type, "Select profile type"%>
<%=
f.select :type, Profile::TYPES,
:prompt => "Select a profile type"
%>
</div>

The drop down menu looks fine. But, how would I check which option is selected? I want to route to a different view based on this selection.

Thanks in advance!

The logic of routing to a different view should occur in your controller. When the user submits this form, check the value of the params, and perform your logic to route to a view:

class ExampleController

  def routing
    case params[:example][:type]
    when 'foo'
      redirect_to foo_path
    when 'bar'
      redirect_to bar_path
  end
end

You can create a custom action name, since this routing isn't one of the CRUD operations. You will need to place this route into the config/routes.rb file if it is a custom name.

Optionally, you can bind to the select's onChange event, as mentioned by others to auto-submit the form when the user changes the value. This would still send the data to the controller and perform a redirect. The advantage to this approach is that you can keep your route information out of Javascript, and in the Rail's controller.

More on Rails routing can be found here: http://guides.rubyonrails.org/routing.html More on Javascript binding to onChange can be found here: http://www.w3schools.com/jsref/event_onchange.asp

You should be able to use jQuery or any other popular Javascript framework to achieve this -- either attach an onChange listener or set the value somewhere and check it. Events, yay, etc.

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