user2630970
user2630970

Reputation: 153

How to query across three models

I have a WorkSpace, Project, User, and Membership models. A user has many memberships, and many projects through memberships. A project belongs to a work space.

Getting the users projects is pretty easy:

user.projects

But reaching across to get the work spaces is tricky. Something like this raises an error of undefined method spaces for collection proxy.

user.projects.work_spaces.unique

How can I get a unique set of work spaces that the user is involved in? (Work Spaces with projects that the user belongs to through memberships).

Upvotes: 0

Views: 114

Answers (2)

Carlos Drew
Carlos Drew

Reputation: 1633

If you are using ActiveRecord, I would suggest leveraging its association methods in order to avoid the verbose code and poorer performance of .collect(&:work_spaces).flatten.uniq.

class User < ActiveRecord::Base
  has_many :memberships
  has_many :projects, through: :memberships
  has_many :work_spaces, through: :projects
end

You will then be able to ask for user.work_spaces.

Upvotes: 2

Dylan Markow
Dylan Markow

Reputation: 124419

user.projects is a collection of projects, which is why you can't call work_spaces directly on it.

You can use Enumerable's collect method (or map) to grab all the collections, then strip out the duplicates:

user.projects.collect(&:work_spaces).flatten.uniq

Upvotes: 1

Related Questions