【问题标题】:Joining multiple tables while accumulating conditions在累积条件的同时连接多个表
【发布时间】:2012-09-14 20:23:11
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

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

    conds = joins(:product, { :product => :categorizations })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-06-10
      • 2021-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-30
      相关资源
      最近更新 更多