Rails using joins retrieve repeated column

174 Views Asked by At

My association

class Website < ApplicationRecord
  has_many :settings
  has_one :shop
end

Setting and Shop tables value are:

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] 

Using joins

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

I am getting repeated value

[[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]]

The result i want like

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

How can i resolve the problem?

Thanks in advance :)

1

There are 1 best solutions below

0
Sibevin Wang On

I am not sure why you expect the result is [[2, 4], [2, 1], [4, 1], [0, 0], [0, 0], [0, 0]](maybe it is a typo?), but if you want to get the non-repeat result from the join query, you can use 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]]