diff --git a/README.md b/README.md index 4ec3695..1f37ece 100644 --- a/README.md +++ b/README.md @@ -62,11 +62,11 @@ class Book < ActiveRecord::Base # prefacers for the book via a join table has_many :forewords - has_many :foreworders, through: :forewords, source: :user + has_many :foreworders, -> { distinct }, through: :forewords, source: :user # illustrators for the book via a join table has_many :illustrations - has_many :illustrators, through: :illustrations, source: :user + has_many :illustrators, -> { distinct }, through: :illustrations, source: :user # editors for the book via a join table has_many :edits @@ -121,16 +121,16 @@ book.contributors.where(id: editor.id) # => [#] book.contributors.to_sql -# => SELECT * FROM users WHERE id IN ( +# => SELECT DISTINCT * FROM users WHERE id IN ( # SELECT id FROM users WHERE id = 1 # UNION # SELECT users.id FROM users INNER JOIN prefaces ON users.id = prefaces.user_id WHERE prefaces.book_id = 1 # UNION # SELECT users.id FROM users INNER JOIN forewords ON users.id = forewords.user_id WHERE forewords.book_id = 1 # UNION -# SELECT users.id FROM users INNER JOIN illustrations ON users.id = illustrations.user_id WHERE illustrations.book_id = 1 +# SELECT DISTINCT users.id FROM users INNER JOIN illustrations ON users.id = illustrations.user_id WHERE illustrations.book_id = 1 # UNION -# SELECT users.id FROM users INNER JOIN edits ON users.id = edits.user_id WHERE edits.book_id = 1 +# SELECT DISTINCT users.id FROM users INNER JOIN edits ON users.id = edits.user_id WHERE edits.book_id = 1 # ) # example of more advanced querying e.g. preloading the union diff --git a/spec/union_of_spec.rb b/spec/union_of_spec.rb index cae8045..f9e72c6 100644 --- a/spec/union_of_spec.rb +++ b/spec/union_of_spec.rb @@ -1391,10 +1391,10 @@ def owned = where(owner: proxy_association.owner) has_many :foreworders, through: :forewords, source: :user has_many :illustrations - has_many :illustrators, through: :illustrations, source: :user + has_many :illustrators, -> { distinct }, through: :illustrations, source: :user has_many :edits - has_many :editors, through: :edits, source: :user + has_many :editors, -> { distinct }, through: :edits, source: :user has_many :contributors, -> { distinct }, class_name: 'User', union_of: %i[ author @@ -1485,7 +1485,7 @@ def owned = where(owner: proxy_association.owner) ) UNION ( - SELECT + SELECT DISTINCT users.id FROM users INNER JOIN illustrations ON users.id = illustrations.user_id @@ -1494,7 +1494,7 @@ def owned = where(owner: proxy_association.owner) ) UNION ( - SELECT + SELECT DISTINCT users.id FROM users INNER JOIN edits ON users.id = edits.user_id