Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord query across three models?

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 #):

like image 221
AnApprentice Avatar asked Jul 25 '26 11:07

AnApprentice


1 Answers

My two solutions are:

  • clean, simple standard rails meta-code, no custom finders
  • efficient, fetches in one SQL query, no N+1 issues
  • compliant, meaning you can still build, create etc. on the relation

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

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

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.

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
like image 180
clyfe Avatar answered Jul 28 '26 01:07

clyfe