Reputation: 429
How can I have linked drop downs on a rails page. both drop downs will be coming from database.
for example If first drop down is category
(coming form category
table). second drop down, products
, also coming from db, will be populated based on selection of first drop down?
Upvotes: 3
Views: 986
Reputation: 3696
You can create your dropdown using collection_select helper and on selection of a value in one drop down you can send the ajax request back to your controller action to update another element of the page with the new drop down and products, like so
<%= collection_select(:category, :some_category_method_name,
Category.all, :id, :category_name,
{:prompt => 'Select'},
{ :onchange => remote_function(:url => {:action => 'get_products'},
:with => "'id=' + this.value")})
%>
<div id='product_dropdown'></div>
So basically what the above code doing is, generating a drop down for category and on changing the selected value from this drop down will send a request to the action 'get_products' with the id of the selected category. Then in that method you can get all products with that category and update the 'product_dropdown' element with a new partial that has a dropdown for products.
def get_products
@category = Category.find(params[:id)
render :update do |page|
page.replace_html 'product_dropdown',
:partial => 'partial_name_in_which_you_have_product_drop_down',
:locals => {:products => @category.products}
end
end
Hopefully this should get you started.
If you are not sure how collection_select works then here is the docs
Upvotes: 3