给定两个查询,例如:

@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
                          ]

最佳答案

这是一种可能适合您的手动 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 不会删除单个查询中的重复项。

关于ruby-on-rails - Rails - 两个查询在没有 SCOPE 的情况下组合它们,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4766549/

10-13 04:50