Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 筛选属于其他模型的模型_Ruby On Rails_Ruby_Filter - Fatal编程技术网

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