Q:

rails select records which have duplicates

For my case i want to select all duplicates records from table
for example
table1 

id | name | sub_name

1  | joe  | j1
2  | tim  | t1 
3  | ben  | b1    
4  | joe  | j2    
5  | tim  | t2 

i vant to select 
 [#<table1 id: 1, name: "joe", sub_name: "j1">, #<table1 id: 4, name: "joe", sub_name: "j2">, #<table1 id: 2, name: "tim", sub_name: "t1">, #<table1 id: 5, name: "tim", sub_name: "t2">]

 and then display

 joe
  - j1
  - j2
 tim
  - t1
  - t2

Can anybody help me to do this using AR or SQL.
i tried this query Table1.group(:name).having("count(*) > 1"
but the result was 
[#<table1 id: 1, name: "joe", sub_name: "j1">, #<table1 id: 2, name: "tim", sub_name: "t1">]
or result.count returns
{["joe]=>2, ["tim"]=>2}

A:

Well I don't know if this is the most efficient way but you could:
names_with_multiple_rows = Table1.group(:name).having("count(*) > 1")
res = names_with_multiple_rows.inject({}) do |h, m|
  h[m.name] = Table1.select(:sub_name).where(name: m.name)
  h
end

Now res is a hash where the keys is the name and the values are the sub_names.

