2016-04-30 74 views
1

我有以下型號推進活動記錄加入

Items 
Customisations 
Property Maps 

,象這樣社團 -

**Customizations** 
belongs_to :item 
has_many :property_maps, as: :mappable 

**Items** 
    has_many :customizations 
    has_many :property_maps, as: :mappable 

**Property Maps** 
belongs_to :mappable, polymorphic: true 

我實現了一個相當不錯的過濾系統,考慮到只是項和屬性,像這樣 -

def self.filter_in_properties(property_ids, group_name) 
      joins(:property_maps).joins('JOIN property_maps '+group_name+' ON '+group_name+'.mappable_id = items.id AND '+group_name+'.property_id IN ('+property_ids.to_s.tr('[', '').tr(']', '').tr('"', '') +')') 
    end 

和我在控制器中調用它們 -

@items_without_pagination.filter_in_properties(params[:color_filter], 'color_filter').uniq 

我該如何構建一個過濾系統,以便在例如用戶搜索紅色的顏色時,它不僅返回具有紅色屬性的項目,而且返回具有紅色屬性的自定義項目?

回答

0

您可以在項目/自定義結合使用joins,包括自定義在查詢中filter與顏色'red'

Item.joins(:customizations).where("items.color = '?' OR customizations.color='?'", 'red').uniq 

這將返回項情形之一item.color'red'或任何item.customizations是紅色的。

請注意,color應該是itemscustomizations表中的列。

0

這差不多就是我終於實現了 -

def self.filter_in_properties(property_ids, group_name) 
    return all if property_ids.blank? 
    joins('LEFT JOIN customizations as prop_customizations ON prop_customizations.item_id = items.id') 
.joins('LEFT JOIN property_maps '+group_name+' ON '+group_name+'.mappable_id = items.id') 
    .joins('LEFT JOIN property_maps '+group_name+'_customization ON '+group_name+'_customization.mappable_id = prop_customizations.id') 
    .where('('+group_name+'.property_id IN ('+property_ids.to_s.tr('[', '').tr(']', '').tr('"', '') +')) OR ('+group_name+'_customization.property_id IN ('+property_ids.to_s.tr('[', '').tr(']', '').tr('"', '') +'))').distinct 
end