LoginSignup
2
0

More than 3 years have passed since last update.

has_many throughで重複したデータをdistinctしたい

Posted at

問題

例えばこういう関係のモデルがあったとして

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

すごく便利(ここを参照しました)

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0