0

I have the following 2 models:

Projects, has_many projects
Users belong_to Projects

@project = Project.find(1)
@project.users --- outputs a lot of users

What I want to be able to do is the following: Given a list of say 3 projects (1,4,11), iterate over each project's users and build an object with all the users across the three projects, first combining, while not duplicating.

Here is what I have so far, but it's not working correctly:

  @aggregate_users = Array.new


  params[:project_list].split(/, ?/).each do |project|
      @project_temp = Project.find(project)
      @project_temp.users.each do |user|
        @aggregate_users << user
      end
  end

Suggestions? Also, how to avoid duplicate users from being added? Thanks

2
  • 1
    If ":user belongs_to :project", how is it possible that you get duplicate users? Commented Apr 15, 2011 at 22:47
  • Agree with @tokland here - if users belong_to projects, then "John" who belongs to Project A is technically a dffierent user than "John" from Project B (even though they have the same name, they'll be separate objects in your DB - even .uniq! won't help you here). Perhaps it would make more sense to use has_and_belongs_to_many? Commented Apr 15, 2011 at 23:55

2 Answers 2

5

Pure Ruby approach:

@users = Project.find(project_ids).map(&:users).flatten.uniq

SQL approach (as you say a user belongs to a project):

@users = User.where(:project_id => project_ids)
Sign up to request clarification or add additional context in comments.

Comments

0

I would start by sticking to rails convention

  class Project < ActiveRecord::Base
        has_many :users
  end

  class User < ActiveRecord::Base
        belongs_to :project
  end

Next,lets say you have @projects, which holds those three projects you mentioned (or more)

  @needed_users = Array.new

  @projects.each do |project|
     project.users.each do |user|
        if !@needed_users.includes?(user)
           @needed_users.push(user)
        end
     end
  end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.