John
John

Reputation: 634

Check how many times a row repeats in a table

I have some records in a table, with the columns: id, link, title.

Few rows in the db have the link column with the same value, and I want to know how for link how many rows have the same value.

I have an idea on how to do it but I think there is a much easy solution.

o = Repo.select(:link).distinct
o.each do |l|
  Repo.where(link: l.link).size
end

Thank you.

Upvotes: 0

Views: 47

Answers (2)

AbM
AbM

Reputation: 7779

As per my comment above, the group method will group the query based on selected parameter. So:

Repo.group(:link).count

will return a Hash such as:

{link1=> count_for_link_1, link2=> count_for_link_2 ...}

Upvotes: 0

Kuldeep
Kuldeep

Reputation: 884

You can use:

Repo.select('count(*)').group(:link)

Upvotes: 1

Related Questions