Steve_D
Steve_D

Reputation: 553

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. For a given option in the drop down I need to be able to pass 3 values. Is it possible to do this using the 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

<%= 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?

Upvotes: 3

Views: 3302

Answers (2)

phts
phts

Reputation: 3925

According ruby on rails f.select options with custom attributes there two way:

1) Store your values in each option as data attributes. Create an event listener on your select tag which will add hidden inputs with correct names based on option data attributes and values. 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.

Upvotes: 1

MrYoshiji
MrYoshiji

Reputation: 54882

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

Upvotes: 1

Related Questions