Rails - two queries combining them without SCOPES

Given two requests, for example:

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

I want to combine two:

@users_to_show = @users1 + @users2

The problem is how to prevent duplicate users from showing. Is there a way to combine the two (array?), And then make sure duplicate entries are deleted?

thank

UPDATED:

# This QUERY gives all of a user 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
                          ]
+3
source share
1 answer

This is a manual SQL approach that might work for you:

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

EDIT : UNION will generate duplicate records between two queries.

EDIT . Make sure that each of the queries does not duplicate independently. The union will not remove duplicates within individual requests.

+2
source

Source: https://habr.com/ru/post/1787093/


All Articles