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:
1.
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
2.
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.