rails count double entries

2019-03-03 14:49发布

问题:

I have a join table:

<% @users.each do |user| %>
<li><%= user.user_id %><%= user.user.name %></li>

gives me

  • 1 fred
  • 1 fred
  • 9 charlie

Well.. thanks so far for the answers. I can see that I was not precise enough to explain what I need.

<% @users.each do |user| %>
<li><%= user.user_id %><%= user.user.name %></li>

is the result on an query. So the result could be 10 different user or some could be double or triple. I want to mark them when they appear multipe. I dont want to find out double entries in my database.....

So I have to find out weather in |user| are mutiple val with the same user_id..to get a true/false Hope this makes it more clear. Right now I dont have clou how to archieve this.

回答1:

suppose you have two tables users and details

From a very little i got your question, i think you want all the users who has duplicate details

your sql should be like following

double_details = SELECT u.* FROM users u LEFT JOIN details on d.user_id = u.id 
                            GROUP BY 'u.user_id' HAVING (COUNT(d.id))  > 1


回答2:

Model.group(:user_id).select("user_id, COUNT(*) as total").find_all{|i| i.total > 1}

Replace Model with your model.



回答3:

If the user table references itself, then something like user.users.count should return the amount of other users referencing this one.