0
votes

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:

  1. How would I show only the Products with a scope of active? ie: Product.active

  2. 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()
2

2 Answers

0
votes

1)How would I show only the Products with a scope of active?

You are right no you need to define a scope for Products so you can easily reference it with .active. You want to pop something like this in your ProductsHelper file to give you access to a call like this.

scope :active, lambda {|prod_id| where("active= ? AND id= ?", true, prod_id}

2) How would I show only Categories that have active products attached to them?

Again I would go ahead and attach a scope to categories that serves your needs. But there are other options out there. You can tryout some class methods which are pretty sexy and would definitely serve your needs as well. Here is an interesting post about it Named Scopes are Dead

0
votes

My point of view:

1st:

product.rb

scope :active, -> {where(active: true)}

2nd:

cateogry.rb

has_many :active_products, class: 'Product', :conditions => {:active => true}

then you can call: category.active_products