推进活动记录加入
问题描述:
我有以下型号推进活动记录加入
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
我该如何构建一个过滤系统,以便在例如用户搜索红色的颜色时,它不仅返回具有红色属性的项目,而且返回具有红色属性的自定义项目?
答
您可以在项目/自定义结合使用joins
,包括自定义在查询中filter
与颜色'red'
:
Item.joins(:customizations).where("items.color = '?' OR customizations.color='?'", 'red').uniq
这将返回项情形之一item.color
是'red'
或任何item.customizations
是红色的。
请注意,color
应该是items
和customizations
表中的列。
答
这差不多就是我终于实现了 -
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