在累积条件的同时连接多个表

时间:2012-09-14 20:23:11

标签: ruby-on-rails ruby-on-rails-3 arel

我有一个类方法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

1 个答案:

答案 0 :(得分:2)

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

conds = joins(:product, { :product => :categorizations })
相关问题