how to have linked drop downs in a rails form
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开发者_StackOverflow form category
table). second drop down, products
, also coming from db, will be populated based on selection of first drop down?
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
Easiest is to use one Javascript widget that will provide a tiered menu.
Here's one from YUI. I'm sure there are others based on other toolkits.
精彩评论