title: Speed up ActiveRecord insert for a given loop
body: <h1>The Setup</h1>
  
  <pre><code>rails new xyz
  cd xyz
  rails g scaffold Donor name
  rails g scaffold Recipient name
  rails g scaffold Donation amount:integer donor:references recipient:references
  rails g scaffold Search query
  rails g model SearchResult search:references donation:references
  </code></pre>
  
  <p>Rails 5.2, Ruby 2.5.1 and Postgresql.</p>
  
  <h1>The Problem</h1>
  
  <p>We are talking about a big data set of a couple of million entries, and would like to optimize the code below which creates tens of thousands of entries in <code>SearchResult</code>. It takes more than 10 seconds to insert it. Is there a way to optimize the following code so that it is faster?</p>
  
  <pre><code>search = Search.new(query: "Smith")    
  Donation.joins(:donor).
           where("donors.name like ?", "%#{search.query}%").each do |donation|
    search.search_results.build(donation: donation)
  end
  Donation.joins(:recipient).
           where("recipients.name like ?", "%#{search.query}%").each do |donation|
    search.search_results.build(donation: donation)
  end
  search.save
  </code></pre>
  
  <p>I'm not a big fan of using RAW SQL in Rails, but if there is a way of solving this in pure SQL which would be faster, than that could be possibility too.</p>