繁体   English   中英

如何使用 RoR 中的过滤器分类进行查询?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM