I have a Category selection that populates a Product selection:
<%= f.collection_select(:category_id, Category.active.sorted, :id, :name, :include_blank => true ) %>
Based on the Category selected, the products with that category_id are loaded into next selection:
<%= f.grouped_collection_select :product_id, Category.active.sorted, :products, :name, :id, :name, include_blank: true %>
Two Questions:
How would I show only the Products with a scope of active? ie:
Product.active
Along the same lines, in the Category selection list, how would I show only Categories that have active products attached to them? ie: if the selected category has no products or products that are not active, the Category doesn't show in the first dropdown.
JS code:
$('#request_product_id').parent().hide()
products = $('#request_product_id').html()
emptyOption = $('<option />').attr('value', '');
$('#request_category_id').change ->
category = $('#request_category_id :selected').text()
options = $(products).filter("optgroup[label='#{category}']").prepend(emptyOption).html()
if options
$('#request_product_id').html(options)
$('#request_product_id').parent().show()
else
$('#request_product_id').empty()
$('#request_product_id').parent().hide()