[英]How to query with with filter classifications in RoR?
寻找一种基于labels
过滤clothes
的方法,需要考虑labels
的分类,这样不同的分类都需要满足(AND),相同的分类被连接(OR)。
例如,可以满足以下期望:
查询:( Blue(classification: Color)
或Green(classification: Color)
)和On Sale(classification: Discount)
或者
查询: Blue(classification: Color)
和( Aloha(classification: Style)
或Knit(classification: Style)
)
class Clothes < ApplicationRecord
string :name
has_many :clothes_label
end
class ClothesLabel < ApplicationRecord
belongs_to :clothes
belongs_to :label
end
class Label < ApplicationRecord
string :name # blue, aloha, knit, black
string :classification # color, style
has_many :clothes_label
end
我希望能够只查询"Blue and Aloha" or "Green and Aloha" clothes
:
Clothes.for_label_classfications(
color: ['blue', 'green'],
style: ['aloha']
)
在Clothes
model 中定义label
关联:
has_one :label, through: : clothes_label
然后在根据 label 分类返回衣服的Clothes
model 中定义如下 scope:
scope :for_label_classfications, -> (classification:, name:) { joins(:label).where(label: {classification: classification, name: name}) }
现在,当您可以运行多个查询以根据分类获取衣服并将它们组合起来时:
Clothes.for_label_classfications(classification: 'style', name: ['aloha']) +
Clothes.for_label_classfications(classification: 'color', name: ['blue', 'green'])
或者您也可以简单地运行单个查询,假设不同的分类不能没有具有相同名称的数据。 例如,样式分类不能以绿色作为名称:
Clothes.for_label_classfications(classification: ['style', 'color'], name: ['aloha', 'blue', 'green'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.