如何使用 Rails 5.2 中的关系属性通过关系过滤 has_many 中的记录?

How to filter records in has_many through relationship using a relation's attribute in Rails 5.2?

我通过 N-N 关系管理基于链接值列表的分类。由于关系必须服从特定的顺序,我实现了一个中间模型 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 模型包括一个 sort_order 属性来定义链接 values_lists.

的过滤或排序

我可以轻松检索给定分类的所有 values_lists:

My_lists = @classification.values_lists

但是我怎样才能优雅地检索通过连接给定 sort_order 分配的 values_lists?

您可以使用 ActiveRecord 的扩展来实现这一点。您可以查看文档以获取更多详细信息 (link here),但作为您的特定情况的示例,您可以执行以下操作:

class Classification < ApplicationRecord
  has_many :values_lists_classifications
  has_many :values_lists, through: :values_lists_classifications do
    def with_sort_order(sort_order)
      where('values_lists_classifications.sort_order = ?', sort_order)
    end
  end
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

然后你可以 access/filter 像这样:@classification.value_lists.with_sort_order(sort_order)