简体   繁体   English

Ruby on Rails:将下拉菜单的选定值传递给函数

[英]Ruby on Rails: Passing the selected value of a drop down menu to a function

I'm using devise and I'm trying to pass the selected value of a drop down menu to a function, but it is not working. 我正在使用devise,并且试图将下拉菜单的选定值传递给函数,但是它不起作用。 The data is being stored in a model called user. 数据存储在称为用户的模型中。

<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
<%= devise_error_messages! %>
<%= f.select :role, options_for_select([["Job Seeker", "candidate"], ["Employer",  "employer"], ["Recruiter", "recruiter"]]) %>

<% if params[:role] == "candidate" %>
<div><%= f.label :travel %><br />
<%= f.text_field :travel %></div> 
<%  end 
if params[:role] == "employer" || params[:role] == "recruiter"
%>
<div><%= f.label :company %><br />
<%= f.text_field :company %></div>
<% end %>
<% end %>

It looks to me as though your conditionals should use the resource object, eg <% if resource.role == "employer" %> 在我看来,您的条件句应该使用资源对象,例如<% if resource.role == "employer" %>

You might want to pass the current value for resource.role as an argument for options_for_select 您可能希望将resource.role的当前值作为options_for_select的参数传递

options_for_select([["Job Seeker", "candidate"], ["Employer",  "employer"], ["Recruiter", "recruiter"]], resource.role)

It seems to me that you want the user to select a role, then display different fields depending on the selected role. 在我看来,您希望用户选择一个角色,然后根据所选角色显示不同的字段。 Correct me if I'm wrong. 如果我错了纠正我。 From the portion of code which you posted it's impossible to tell exactly what your approach is. 从您发布的代码部分中,无法确切说明您的方法是什么。 There are several ways to solve the problem including: 有几种解决问题的方法,包括:

  1. Post the form with the selected role and re-render the form. 发布具有所选角色的表单,然后重新呈现该表单。 The process would be similar to re-rendering forms when there is eg a validation error. 当存在例如验证错误时,该过程将类似于重新呈现表单。

  2. Break up the form into multiple stages 将表格分为多个阶段

  3. Use javascript to detect when the value of the select has changed and then update the form by showing and hiding fields. 使用javascript来检测select的值何时已更改,然后通过显示和隐藏字段来更新表单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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