简体   繁体   English

使用Rails select_tag传递多个值

[英]Pass more than one value using Rails select_tag

I am using the rails form_tag helper, with the select_tag for a drop down within the form. 我使用rails form_tag helper,在表单中使用select_tag下拉列表。 For a given option in the drop down I need to be able to pass 3 values. 对于下拉列表中的给定选项,我需要能够传递3个值。 Is it possible to do this using the select_tag? 是否可以使用select_tag执行此操作?

The data that is being used to populate the drop down is formatted as an array of hashes, below is an example of the format of a given item in the array. 用于填充下拉列表的数据被格式化为哈希数组,下面是数组中给定项的格式示例。

{ name: page['name'], page_id: page['id'], access_token: page['access_token'] }

So after the form is submitted I want to get each of those values in my controller as parameters. 因此,在提交表单后,我希望将控制器中的每个值作为参数。

The form using the select_tag 使用select_tag的表单

<%= form_tag '/facebook_credentials' do %>
  <%= select_tag(:option, options_for_select(session['facebook_pages'].collect { |x| [x[:name] ] }) ) %>
  <%= submit_tag 'Save', class: 'button expand' %>
<% end %>

By default the select_tag only allows for one value, is there a work around to this or a more efficient way to achieve the outcome I am looking for? 默认情况下,select_tag只允许一个值,是否有解决方法或更有效的方法来实现我正在寻找的结果?

You could find the "other values of the hash" by getting the hash which you just selected the name: 您可以通过获取刚刚选择名称的哈希来找到“哈希的其他值”:

# view
select_tag(:option, options_for_select(session['facebook_pages'].collect { |x| [x[:name] ] })

# controller's action (where you submit your form)
selected_hash = session['facebook_pages'].find{ |x| x[:name] == params[:option] }

This code relies on the fact that each hash in the options of the select_tag has a uniq :name 's value 此代码依赖于select_tag选项中的每个哈希都具有uniq :name的值这一事实

According ruby on rails f.select options with custom attributes there two way: 根据ruby on rails f.select选项有自定义属性有两种方式:

1) Store your values in each option as data attributes. 1)将您的值存储在每个option作为数据属性。 Create an event listener on your select tag which will add hidden inputs with correct names based on option data attributes and values. 在select标签上创建一个事件监听器,它将根据选项数据属性和值添加具有正确名称的隐藏输入。 These hidden input data will be sent to the server. 这些隐藏的输入数据将被发送到服务器。

2) Make option values with some specific format combining your data and then parse them on the server. 2)使用某种特定格式组合您的数据option值,然后在服务器上解析它们。

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

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