0
votes

I have two models with a many-to-many relationship defined through another model. In this case A user belongs to many groups. And each group can have many users. There relationship is defined through a Membership model, which also has the status of their membership i.e.

user.rb

class User < ApplicationRecord
  has_many :memberships
  has_many :groups, through: :memberships
end

group.rb

class Group < ApplicationRecord
  has_many :memberships
  has_many :users, through: :memberships
end

membership.rb

class Membership < ApplicationRecord
  belongs_to :user
  belongs_to :group

  enum status: [ :non_member, :pending, :member ]
end

When I create a new group, It always creates a membership for the user who created it. At a later date other users create memberships for a group.

Within one of my views, I want to show all groups that the current user belongs to. So I can do something like this:

<% @user.groups.each do |group| %>
   <p><%= group.name %>
<% end %>

I then want to show all the groups that a user does not belong to, so that they can request to join. I tried this, but it returns all records, even though my user is a member of one group.

<% Group.joins(:users).where.not(:users => { :id => current_user.id }).each do |group| %>

Is there a better way to achieve this?

1

1 Answers

1
votes
class User < ApplicationRecord

   has_many :memberships
   has_many :groups, through: :memberships


   def unjoined_groups
      Group.where.not(id: group_ids)
   end

   def unjoined_groups_by_membership_status(status)
      Group.includes(:memberships)
        .where.not(id: group_ids)
        .where(memberships: { status: status })
   end

end

Try this instead...