AnApprentice
AnApprentice

Reputation: 110960

Rails - How to build an Array of users

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

Upvotes: 0

Views: 1181

Answers (2)

Daniel
Daniel

Reputation: 3027

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

Upvotes: 0

tokland
tokland

Reputation: 67860

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)

Upvotes: 5

Related Questions