I have three models:
class User < ActiveRecord::Base
has_many :projects, :through => :permissions
class Permission < ActiveRecord::Base
belongs_to :user
belongs_to :project
belongs_to :role
class Project < ActiveRecord::Base
has_many :users, :through => :permissions
It's very easy with the above to get all of a Project's users: @project.users
But what I want to do is get something like this: Get all the Users in all of the user's projects.
So if a user has 3 projects, each with 5 users. I want to query to get all 15 users across all of the user's groups.
I'm trying that with.
current_user.projects.users
but Rails isn't liking that much. current_user.projects works great, but not users.
Suggestions? Ideas? thanks!
UPDATED CODE 3 based on noodl's comments
scope :suggestedContacts, lambda { |user|
users_from_projects = user.projects.reduce([]) {|all_users,prj|
all_users + prj.users
}.uniq
}
ERRORS:
NoMethodError (undefined method `includes_values' for #):
My two solutions are:
You can chain your relation in the user class.
As rails 3.0.x does not yet support nested has_many_through you can use this plugin until rails 3.1
class User < ActiveRecord::Base
has_many :permissions
has_many :projects, :through => :permissions
has_many :users_in_projects, :through => :projects, :source => :user # chain the relation
class Permission < ActiveRecord::Base
belongs_to :user
belongs_to :project
class Project < ActiveRecord::Base
has_many :users, :through => :permissions
current_user.users_in_projects
Another way would be to eager load and reduce (like the other answers have already described, but I'll make it more explicit).
This is more work, less dependencies.
class User < ActiveRecord::Base
has_many :permissions
has_many :projects, :through => :permissions, :include => :users # eager load users
class Permission < ActiveRecord::Base
belongs_to :user
belongs_to :project
class Project < ActiveRecord::Base
has_many :users, :through => :permissions
current_user.projects.map(&:users).reduce(&:+).uniq_by(&:id)
# returns users in current_user's projects, one query, some computations
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With