Rails - 两个查询组合它们没有SCOPES

时间:2011-01-22 06:49:23

标签: ruby-on-rails ruby-on-rails-3

给出两个查询:

@users1 = Users.find_by_company_id(2)
@users2 = Users.find_by_office_id(2)

我想把两者结合起来:

@users_to_show = @users1 + @users2

问题是如何防止重复用户显示。有没有办法将两者结合起来(数组?)然后确保删除重复的记录?

由于

更新:

# This QUERY gives all of a user's project members, people they work with
@project_ids = @projects.map(&:project_id)

@users = User.find_by_sql [
                            "SELECT DISTINCT users.*
                            FROM users 
                              INNER JOIN permissions ON permissions.user_id = users.id 
                            WHERE project_id IN (?) AND permissions.user_id != ?
                            UNION ALL
                            SELECT DISTINCT users.*
                            FROM users
                            WHERE instance_id = ?",
                            @project_ids, current_user.id, current_user.instance_id
                          ]

1 个答案:

答案 0 :(得分:2)

这是一种可能适合您的手动SQL方法:

@users = User.find_by_sql("
     SELECT DISTINCT * FROM USERS WHERE [Place your First complicated where clauses Here]
     UNION
     SELECT * FROM USERS WHERE instance_id = ?
", current_user.instance_id)

修改: UNION将在两个查询之间对重复记录进行精简。

编辑:确保每个查询都不会独立生成重复项。 Union不会删除单个查询中的重复项。