0

我有一个类方法Relationship.with_attributes,用于基于多个输入参数构建复杂范围,以返回Relationship与匹配某些属性的产品关联的对象。在大多数情况下,我匹配的信息都在Product模型上,一切都很好:

def self.with_attributes(attributes)
  if (attributes.nil?)
    scoped
  else # (attributes.class == Hash)
    conds = joins(:product)

    attributes.each do |key, value|
      case key
      when "Category"
        # FIXME This doesn't work yet
        category = Category.find(value)
        categories = [category] + category.descendants
        categories.each { |c| conds.push(["categories.id = #{c.id}"], :or) }
      else
        conds.where(key => value)
      end
    end
  end
  conds
end

Categorizations挑战是当我的属性是一个类别时,我无法确定如何加入模型。非常感谢任何建议。缩写型号如下。

class Relationship < ActiveRecord::Base
  belongs_to :product
  …
end

class Product < ActiveRecord::Base
  has_many :relations
  has_many :categorizations
  …
end

class Categorizations < ActiveRecord::Base
  belongs_to :product
  …
end
4

1 回答 1

2

发布后不久我偶然发现了答案。答案是更新conds = joins(:product)为:

conds = joins(:product, { :product => :categorizations })
于 2012-09-14T20:47:43.420 回答