alejorivera
alejorivera

Reputation: 945

Rails: Find array of related objects

This is the code I currently have:

project_ids = ProjectEnrollment.unscoped.where(user: self).pluck(:project_id)
Project.where(id: project_ids)

I'm sure there has to be a better way. Thanks!

Edit: I'm already using the method from the has_many relationship, with scoped projects for another case.

Upvotes: 1

Views: 38

Answers (1)

Logan Serman
Logan Serman

Reputation: 29880

In your User model:

has_many :project_enrollments, -> { unscoped }
has_many :projects, through: :project_enrollments

In your ProjectEnrollment model:

belongs_to :user
belongs_to :project

Then you can do

user.projects

Upvotes: 1

Related Questions