How do I join ActiveRecord after the records have been returned?

I use ActiveRecord in Rails 3 to retrieve data from two different tables in two different databases. These databases cannot connect to each other, but I need to make a simple connection after the fact. I would like to keep the relationship so that I can tie it along the line.

here is a simplified version of what I'm doing

browsers = Browser.all # <-- this is fairly small and can reside in memory events = Event.where(:row_date=>Date.today).select(:name, :browser_id) 

So, as you can see, I want to join browsers with respect to events , where browser_id should equal browsers.name . events is a relation, and I can still add line-by-line sentences to it, so I don’t want to run a db request yet. How to do it?

Edit

For those who would like to see some kind of code for the answer, which I accepted below, here is what I came up with:

 class EventLog < ActiveRecord::Base belongs_to :browser def get_todays_events Event.where(:row_date=>Date.today).select(:name, :browser_id).includes(:browser) end end 

will allow me to get the browser name as follows

 get_todays_events.browser.name 
+4
source share
2 answers

I would do this using: include. Trying to do this in Ruby will bring you nothing but sorrow. You can simply connect to the include object.

+2
source

joins creates SQL joins as expected in current Rails 5:

pry(main)> Customer.joins(:orders).limit(5) Customer Load (0.2ms) SELECT `customers`.* FROM `customers` INNER JOIN `orders` ON `orders`.`customer_id` = `customers`.`id` LIMIT 5 => [#<Customer:0x007fb869f11fe8 ...

This should be much faster, because it requires only one database query, while includes will do 1 + <number of rows in first table> + <number of rows in second table>...

Here's an example where includes requires 1750x, while joins :

 pry(main)> benchmark do Order.joins(:address, :payments, :customer, :packages).all.size > 0.02456 seconds pry(main)> benchmark do [14] pry(main)* Order.includes(:address, :payments, :customer, :packages).all.map(&:zip).max [14] pry(main)*end => 35.607257 seconds 
0
source

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


All Articles