Reputation: 1181
my app has three tables: Users, Organizations and UserOrganizations. The last table holds user_id and organization_id. So every user can have many organizations.
What I want to do now is to select all users that have the same organization_id's in the user_organization table than the current user.
So e. g. if the current user belongs to organizations with ids 3, 6 and 8 I want to select all users that belong to the same organizations.
The question may be stupid and simple but I'm stuck now with that for hours. :-/
Thx
user.rb
has_many :user_organizations
has_many :organizations, through: :user_organizations
organization.rb
has_many :user_organizations
has_many :users, through: :user_organizations
user_organization.rb
belongs_to :organization
belongs_to :user
Upvotes: 0
Views: 1293
Reputation: 3260
You can run through the join table like
UserOrganization.includes(:user)
.where(organization: current_user.organizations)
.map(&:user)
The nice thing here is that by adding includes
you're hinting to ActiveRecord that you're going to need the user and it makes the query more efficient. It should work without the includes
as long as your join table model has the belongs_to
(which yours does). But without the includes
, if you map(&:user)
it'll make N more queries to grab user data (where N is the number of users that match) instead of using a database join to grab that data with the first query.
Upvotes: 2
Reputation: 13886
Try:
user_organizations = current_user.organizations
users_from_same_organization = User.where(organizations: user_organizations)
Upvotes: 0