简体   繁体   中英

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

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM