简体   繁体   中英

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

I manage Classifications based on linked Values lists, through an NN Relationship. As the relations must obey a specific order, I implemented an in-between 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

The ValuesListsClassification model includes a sort_order attribute to define filtering or sorting of the linked values_lists.

I can easily retrieve all the values_lists of a given classification:

My_lists = @classification.values_lists

But how can I elegantly retrieve only the values_lists assigned given sort_order through the join?

You can use ActiveRecord 's extensions to achieve this. You can take a look at the documentation for more details (link here ), but as an example for your particular case, you can do something like this:

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

And then you can access/filter like so: @classification.value_lists.with_sort_order(sort_order)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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