0

I have 3 Models

class User < ActiveRecord::Base
  has_many :teams, :through => :team_memberships
  has_many :team_memberships
end

class Teams < ActiveRecord::Base
  has_many :users, :through => :team_memberships
  has_many :team_memberships

  has_many :clubs, :through => :club_memberships
  has_many :club_memberships
end

class Clubs < ActiveRecord::Base
  has_many :teams, :through => :club_memberships
  has_many :club_memberships
end

I want to be able to get a unique list of clubs that the user is a member of. If I have the following:

@teams = User.last.teams

How can I get a list of clubs that these teams are members of. If there are any duplicates I would like to only show them once in the list.

Currently if I do:

<% @user.teams.each do |t| %>
  <% t.clubs.each do |c| %>
    <%= link_to c.name, c %>
  <% end %>
<% end %>

I obviously get a complete list but I want to remove the duplicates. Can anyone offer a fix?

MikeHolford
  • 1,851
  • 2
  • 21
  • 32

1 Answers1

0

Looks like I can just set up a relationship like so:

class User < ActiveRecord::Base

  has_many :clubs, -> { uniq }, :through => :teams

end

and then reference:

<% @user.clubs.each do |c| %>
  <%= c.name %>
<% end %>

Please let me know if there is a better way!

MikeHolford
  • 1,851
  • 2
  • 21
  • 32
  • Didn't work for me because I'm using Rails 5 not Rails 4. `NoMethodError: undefined method \`extensions' for # Did you mean? extend` See https://stackoverflow.com/a/318146/10245 - use `distinct` instead of `uniq` – Tim Abell Jul 30 '19 at 08:56