Ruby on rails 在累积条件的同时连接多个表
我有一个类方法Ruby on rails 在累积条件的同时连接多个表,ruby-on-rails,ruby-on-rails-3,arel,Ruby On Rails,Ruby On Rails 3,Arel,我有一个类方法Relationship.with_attributes,我使用它基于多个输入参数建立一个复杂的范围,以返回与匹配某些属性的产品相关联的Relationship对象。在大多数情况下,我所匹配的信息都在产品型号上,而且一切正常: def self.with_attributes(attributes) if (attributes.nil?) scoped else # (attributes.class == Hash) conds = joins(:pro
Relationship.with_attributes
,我使用它基于多个输入参数建立一个复杂的范围,以返回与匹配某些属性的产品相关联的Relationship
对象。在大多数情况下,我所匹配的信息都在产品
型号上,而且一切正常:
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
挑战在于,当我的属性是一个类别时,我无法确定如何加入分类
模型。任何建议都将不胜感激。以下是简化模型
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
类关系
发布后不久,我偶然发现了答案。答案是将conds=joins(:product)
更新为:
conds = joins(:product, { :product => :categorizations })