简体   繁体   中英

Rails combine two different active record objects

I have two tables residing in two different databases.

Example:

Users residing in db1 with attributes user_id and name

Audit residing in db2 with attributes id and user_id

User.find_by_sql("SELECT * FROM users")

Audit.find_by_sql("SELECT * FROM audits")

How do I combine result of these two query results based on user_id

Expected Output rows => user_id audit_id name

if you want to do this in ruby you could just use mapping

users = User.find_by_sql("SELECT * FROM users")

audits = Audit.find_by_sql("SELECT * FROM audits")

result = []
users.each do |u|
   result << { 
     user_id: u.id,
     name: u.name,
     audits: audits.find_all { |a| a.user_id == u.id } 
   }
end

result

# result will include all user audits

in map you may build your hash with whatever you like

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