[英]How to filter records in has_many through relationship using a relation's attribute in Rails 5.2?
[英]How to filter records in has_many through relationship using a relation's attribute in Rails 5.2?
我通过 NN 关系管理基于链接值列表的分类。 由于关系必须服从特定的顺序,我实现了一个介于 model 之间的 ValuesListsClassifications:
class Classification < ApplicationRecord
has_many :values_lists_classifications
has_many :values_lists, through: :values_lists_classifications
end
class ValuesListsClassification < ApplicationRecord
belongs_to :classification
belongs_to :values_list
end
class ValuesList < ApplicationRecord
has_many :values_lists_classifications
has_many :classifications, through: :values_lists_classifications
end
ValuesListsClassification model 包括一个sort_order属性来定义链接的 values_lists 的过滤或排序。
我可以轻松检索给定分类的所有 values_lists:
My_lists = @classification.values_lists
但是我怎样才能优雅地检索通过连接分配给定 sort_order 的 values_lists?
这实际上非常简单。 您可以只针对连接表表达一个where
条件:
@classification = Classification.find(params[:id])
@sort_order = params[:sort_order] # Just being clear about where this might come from
@sorted_values_lists = @classification.values_lists.where("values_lists_classifications.sort_order = ?", @sort_order)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.