Jorge Cuevas Jorge Cuevas - 8 months ago 15
Ruby Question

How to assign a variable the current output of a select tag

Hi I'm new to rails and I'm having some trouble with a select tag.

The objective is to assign a value to a variable depending on which name is shown on the select tag.

<%= select('product', 'name' , { |s| [,] }, {}, {:class => "form-control"}) %>

The values display correctly, but I want to assign the currently selected value to a variable so that it can be used later on the same page to display content with the relevant details of the selected product.


@product = currently_displayed_name

I want to know if this is possible with rails and how to do it or if I might need to use another resource.

Tahnk you.


Props to the comments, the answer is that Rails does not give you a way to do that. Depending on what you need to manipulate when user changes select value, you might be able to find a javascript library for it.

Otherwise, you can load the default variable on the page, and then handle the rest with onchange handler:

$('#product_name').change(function() {
  // perform actions on the page with javascript