I'm utilizing rails4 and I am looking for a more efficient way to display the sub-category list based on the category selected in a form. Currently, I have used JavaScript for this functionality but I believe there may be a better solution. Any suggestions?
Users should be able to choose a category from the following:
<div class="field">
<%= f.label :Category %><br>
<%= f.collection_select :category_id, Category.all, :id, :name, { :prompt => true, :selected => @product.category_id } %>
</div>
Once a category is selected, the next field should update accordingly. Currently, #women_category & #men_category are hidden.
<div class="field" id="women_category">
<%= f.label :sub_category %><br>
<%= f.collection_select :sub_category_id, @first_category.sub_categories.all,:id ,:name%>
</div>
<div class="field" id="men_category">
<%= f.label :sub_category %><br>
<%= f.collection_select :sub_category_id, @second_category.sub_categories.all,:id ,:name%>
</div>
If category_id=1 is selected, #women_category is displayed. If category_id=2 is selected, #men_category is shown using JavaScript.
$("select[name='product[category_id]']").change(function(){
if(this.value == '1'){
$("#women_category").show();
$("#men_category").hide();
}else if(this.value == '2'){
$("#women_category").hide();
$("#men_category").show();
}
});
If the categories list grows, managing this setup could become complex. Is there a simpler way to code this? Please provide guidance.