Francois
Francois

Reputation: 10631

Rails 3, how to get the value of select tag item with dynamic parameter name?

how do I get the selected value of this select_tag, here is my code There are multiple forms like these on one page, thats why I use "dropdown_cases#{e.id}"

<%= form_tag "/application/cart", :remote => true do %>
   <%= select_tag "dropdown_cases#{e.id}", options_for_select([ ["6 Bottles", 1], ["12 Bottles", 2], ["18 Bottles", 3], ["24 Bottles", 4], ["30 Bottles", 5], ["36 Bottles", 6], ["42 Bottles", 7]]) %>
   <%= image_submit_tag("/images/none.png", :class => "add_to_cart_submit", :onclick => "add_to_cart_notify(#{e.id});") %>
<% end %>

Lets say the id here is 123 for instance Now my question is how do I access this value params[:dropdown_cases123]


Thanks Joe Pym for the awnser! I would just like to post my findings for future refrence or for other users with the same problem.
view

<% @results_all.each do |e| %>
 <%= form_tag "/application/cart", :remote => true do %>
  <%= select_tag "dropdown_cases[]", options_for_select([ ["6 Bottles", 1], ["12 Bottles", 2], ["18 Bottles", 3], ["24 Bottles", 4], ["30 Bottles", 5], ["36 Bottles", 6], ["42 Bottles", 7]]) %>
  <%= image_submit_tag("/images/none.png", :class => "add_to_cart_submit" %>
 <% end %>
<% end %>

controller

params["dropdown_cases"].each do |cases|
 @this_is_the_dropdown_value = cases.to_i
end

Upvotes: 0

Views: 3267

Answers (1)

Joe Pym
Joe Pym

Reputation: 1836

Use square brackets.

select_tag "dropdown_cases[]", options_for ....

Note the []. Rails will then store this as {"dropdown_cases" => [one option for each form]}.

If it's important to know which select provided which value, you can nest them, so

select_tag "dropdown_cases[bob]", ... 

will provide {"dropdown_cases" => {"bob" => selected_option}}.

Basically, [] stores it in an array, and [key] stores it in a hash with that key.

Upvotes: 2

Related Questions