0

I have a simple has_many through: table

class User < ApplicationRecord
  has_many :memberships
end

class Membership < ApplicationRecord
  enum :status, [:inactive, :active]
  belongs_to :user
  belongs_to :location
end

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

This finds all memberships at a location that are active

Location.first.memberships.active

Is there a clean way to find all users at a location that are active? This does not work

Location.first.users.active

1 Answer 1

3

First solution with simple query is

User
  .joins(:memberships)
  .where(memberships: { location_id: location_id, status: 'active' })

Second solution with Location model modification is

has_many :active_memberships, -> { Membership.active }
has_many :active_users, through: :active_memberships, source: :user

# and then
Location.first.active_users
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.