AlexNikolaev94 AlexNikolaev94 - 1 month ago 16
Ruby Question

Filtering models that belong to other models

I've got two models:

ProductCategory
and
Product
.
Product
model belongs to
ProductCategory
, and product category can have many products accordingly. The case is that I need to implement some kind of filter that would return me
Product
s that belong to specific
ProductCategory
. These are my models:

class ProductCategory < ActiveRecord::Base
has_many :products
end

class Product < ActiveRecord::Base
belongs_to :product_category

# Here I added some kind of filter method
# But I haven't managed how to use it yet

def self.filter(filter)
where(product_category_id: filter) if filter
end
end


And in my controller I added something like this:

class ProductsController < ApplicationController
def index
if params[:product]
@products = Product.filter(params[:product][:product_category]
else
@products = Product.all
end
end
end


But I can't actually manage how to use my filter and I guess I should refactor it a lot. Can anyone help me with that, please?

Answer

Assuming params[:product][:product_category] is the ProductCategory ID.

class ProductsController < ApplicationController
  def index
    if params[:product]
      @category = ProductCategory.find(params[:product][:product_category])
      @products = @category.products
    else
      @products = Product.all
    end
  end
end

If params[:product][:product_category] anything else than ID then use find_by instead of find.

Comments