Reputation: 364
I am wondering how I should go about retrieving information from a mysql database associated with my ruby on rails app. When a user selects a product from the select box, I want to use the value of the selected option to retrieve the product's description and price from the database and then display it in a div. Using the following code:
<select>
<option value='1'>milk</option>
<option value='2'>eggs</option>
<option value='3'>butter</option>
</select>
<div id='product_description'></div>
<div id='product_price'></div>
When a user selects eggs for example, the first div would read: 'chicken babies' and the second div would read: '$2.00'.
My select tag is also populated from the database, if that is important to know.
The code to populate the select:
<select>
<option>Select Add-on</option>
<% for product in @products %>
<option value="<%= product.id %>"><%= product.item %></option>
<% end %>
</select>
I am also using jquery.
I guess I was basically wondering if I should just use an ajax call or if there was some magic rails way to accomplish the task. If I need to use ajax, can I just do it all from the js.coffee file? I can't figure out how to get the selected options value passed on to another file to select the correct row from the products table.
Upvotes: 1
Views: 1071
Reputation: 54882
You should use options_for_select
to generate your options:
http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/
<%= options_for_select([["Dollar", "$"], ["Kroner", "DKK"]]) %>
#generates
<option value="$">Dollar</option>
<option value="DKK">Kroner</option>
Combined with a select_tag
to generate the select:
http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-select_tag
<% options = "<option>Red</option><option>Green</option><option>Blue</option>".html_safe %>
<%= select_tag "colors", options %>
<div id="product_details"></div>
#generates
<select id="colors" multiple="multiple" name="colors[]">
<option>Red</option>
<option>Green</option>
<option>Blue</option>
</select>
<div id="product_details"></div>
In your case:
<% options = options_for_select(@products.map{ |product| [product.item, product.id] }) %>
<%= select_tag('product_search', options) %>
# jQuery
$('#product_search').bind('Click', function(e) {
var selected_product_id = $(this).val();
# Then call the Ajax
$.ajax({url: '/products/details/' + selected_product_id, # URL to contact
type: 'GET',
success: function(data) {
$('#product_details').empty().append(data);
}
});
});
'/products/details/:id'
where :id
represents the product's id (ProductsController#details
).Now you have to code the server side to handle the request, generate the HTML (or responds with JSON, faster but heavier to handle on the client side) and send a response.
Upvotes: 2