Rails 3:如何过滤“ActiveRecord :: Relation”项目?

时间:2011-01-07 00:16:30

标签: ruby-on-rails activerecord filter scope ruby-on-rails-3

productsActiveRecord::Relation。我过滤了一些像这样的产品:

filtered_products = my_filter(products)

,其中

def my_filter(products)
  last_brand_id = last_model_id = nil
  filtered_products = []

  products.each do |product|
    filtered_products << product if (product.model.brand_id != last_brand_id) || (product.model_id != last_model_id)

    last_brand_id = product.model.brand_id
    last_model_id = product.model_id
  end

  filtered_products
end

现在我想订购过滤后的产品:

filtered_products.order(...)

但我不能这样做,因为filtered_products不是ActiveRecord::Relation

我应该如何重写my_filter,以便返回ActiveRecord::Relation

或者,有更好的解决方案吗?

1 个答案:

答案 0 :(得分:0)

我建议您将'my_filter'方法转换为类方法或范围,以便保留对象。

编辑1:

让我们试着为您提供更广泛的解决方案:

首先,声明你的过滤功能:

def my_filter(product)
  @last_brand_id ||= nil
  @last_model_id ||= nil
  test = (product.model.brand_id != last_brand_id || product.model_id != last_model_id)
  @last_brand_id = product.model.brand_id
  @last_model_id = product.model_id
  test
end

然后获取您想要的产品:

filtered_products = products.select{|p| p if my_filter(p)}