0

私の協会

class Website < ApplicationRecord
  has_many :settings
  has_one :shop
end

設定とショップ テーブルの値は次のとおりです。

2.6.1 :003 > Setting.all.pluck(:records)
=> [2, 2, 4, 0, 0, 0]

2.6.1 :003 > Shop.all.pluck(:records)
=> [4, 1, 1] 

結合の使用

Website.joins(:settings, :shop).where("websites.id = ?", 2).pluck("settings.records", "shops.records")

繰り返し値を取得しています

[[2, 4], [2, 1], [2, 1], [2, 4], [2, 1], [2, 1], [4, 4], [4, 1], [4, 1], [0, 4], [0, 1], [0, 1], [0, 4], [0, 1], [0, 1], [0, 4], [0, 1], [0, 1]]

私が欲しい結果

[[2, 4], [2, 1], [4, 1], [0, 0], [0, 0], [0, 0]]

どうすれば問題を解決できますか?

前もって感謝します :)

4

1 に答える 1

0

結果が期待される理由はわかりませんが[[2, 4], [2, 1], [4, 1], [0, 0], [0, 0], [0, 0]](おそらくタイプミスですか?)、結合クエリから非繰り返し結果を取得したい場合は、group+を使用できますdistinct

Website.joins(:settings, :shop).where("websites.id = ?", 2).group("settings.records", "shops.records").distinct.pluck("settings.records", "shops.records")
=> [[0, 1], [0, 4], [2, 1], [2, 4], [4, 1], [4, 4]]
于 2020-02-29T00:49:05.460 に答える