Uniq / Distinct Results in :through associations 通过配置 Rails

Uniq / Distinct Results in :through associations by configuring Rails

我有以下模型设置

   class Tale < ActiveRecord::Base
   has_many :tale_culture_joins
   has_many :cultures, through: :tale_culture_joins, dependent: :destroy, crud: true, index: true
   has_many :tale_purpose_joins
   has_many :purposes, through: :tale_purpose_joins, dependent: :destroy, crud: true, index: true
   has_many :tale_book_joins
   has_many :books, through: :tale_book_joins, dependent: :destroy, crud: true, index: true
   has_many :tale_keyword_joins
   has_many :keywords, through: :tale_keyword_joins, dependent: :destroy, crud: true, index: true
   has_many :tale_character_joins
   has_many :characters, through: :tale_character_joins, dependent: :destroy, crud: true, index: true
   has_many :tale_moral_joins
   has_many :morals, through: :tale_moral_joins, dependent: :destroy, crud: true
   has_many :values, through: :morals, index: true
   has_many :tale_event_joins
   has_many :events, through: :tale_event_joins, dependent: :destroy, crud: true

   end

   Tale -> Moral -> Value
   Tale(1) -> Moral(1,2)
   Moral(1) -> Value(1,2)
   Moral(2) -> Value(2,3)
   Tale(1).values # => [1,2,2,3]

我理解它背后的原因,我可以将 rails 配置为不仅 return 还 query/build 使用 uniqs 增加 return 值,以便 uniq 条件是传递给 sql 查询本身

如果我没理解错的话,例如,您希望能够执行 Table.events 并获取一组独特的事件。您可以像这样获得 events 的这种行为:

has_many :events, -> {uniq}, through: :tale_event_joins, dependent: :destroy, crud: true

您可以将类似的 -> {uniq} 范围包含在您想要唯一集合的任何关系中。