Ruby on rails 筛选属于其他模型的模型
我有两种型号:Ruby on rails 筛选属于其他模型的模型,ruby-on-rails,ruby,filter,Ruby On Rails,Ruby,Filter,我有两种型号:ProductCategory和Product产品模型属于产品类别,产品类别可以有很多相应的产品。这种情况下,我需要实现某种过滤器,它将返回属于特定ProductCategory的productss。这些是我的模型: class ProductCategory < ActiveRecord::Base has_many :products end class Product < ActiveRecord::Base belongs_to :product_ca
ProductCategory
和Product
产品
模型属于产品类别
,产品类别可以有很多相应的产品。这种情况下,我需要实现某种过滤器,它将返回属于特定ProductCategory
的products
s。这些是我的模型:
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
class ProductCategory
在我的控制器中,我添加了如下内容:
class ProductsController < ApplicationController
def index
if params[:product]
@products = Product.filter(params[:product][:product_category]
else
@products = Product.all
end
end
end
class ProductsController
但是我实际上无法管理如何使用我的过滤器,我想我应该经常重构它。有人能帮我吗?假设
参数[:product][:product\u category]
是ProductCategoryID
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
class ProductsController
如果
params[:product][:product_category]
ID以外的任何内容则使用find_by
而不是find
我建议使用scope而不是class方法。如果您有关联,为什么需要过滤器?您可以获取category.products