[英]Rails - How to build an Array of users
I have the following 2 models: 我有以下2种型号:
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. 我要执行的操作如下:给定一个说3个项目(1、4、11)的列表,遍历每个项目的用户,并与这三个项目中的所有用户一起构建一个对象,首先合并,但不合并复制。
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: 纯Ruby方法:
@users = Project.find(project_ids).map(&:users).flatten.uniq
SQL approach (as you say a user belongs to a project ): SQL方法(正如您所说的, 用户属于项目 ):
@users = User.where(:project_id => project_ids)
I would start by sticking to rails convention 我将从坚持Rails约定开始
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) 接下来,假设您有@projects,其中包含您提到的三个项目(或更多项目)
@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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.