問題
例えばこういう関係のモデルがあったとして
class User < ApplicationRecord
has_many :lists
end
class List < ApplicationRecord
belongs_to :user
belongs_to :product
end
class Product < ApplicationRecord
has_many :lists
end
UserはListを複数持っていて、各ListはProductを参照していて...
Userに関連するProduct全部持ってきたい...
解決方法
class User < ApplicationRecord
has_many :lists
# これだとListの数分重複するProductが返ってくる
# has_many :products, through: :lists
# distinctを差し込んでやる
has_many :products, ->{ distinct }, through: :lists
end
すごく便利(ここを参照しました)