title: ActiveStorage: checking if .attached? for a collection that has attachments preloaded (while avoiding n+1 queries of attached? method)
body: <p>In my Rails 5 application, building a JSON API &amp; using Activestorage for my attachments:</p>
  
  <p>To avoid accessing an attachment that doesn't exist, I am using this <a href="https://stackoverflow.com/a/54205181/7588447">if condition as shown in this answer</a> but unfortunately this if condition makes a SQL query to check if the attachment is available or not, causing n+1 queries although I have already included (pre-loaded) the attachments for the records I have</p>
  
  <p>How to check if the attachment exist on a record without hitting the DB, if I have preloaded the attachments already?</p>
  
  <p>I tried to use .nil? but that will give a false positive that there is attachment even if there isn't (as shown below)</p>
  
  <pre><code>ActionView::Template::Error (to_model delegated to attachment, but attachment is nil):
    if !product.logo.nil?
      json.logo_img url_for(product.logo)
  </code></pre>
  
  <p><code>.attached?</code> check works but causes the n+1 queries:</p>
  
  <pre><code>  if product.logo.attached?
      json.logo_img url_for(product.logo)
  </code></pre>
  
  <p>So while the below code looks very ugly, it works, preloading the attachments for all the records at once, but when checking if an attachment exists => this leads to n+1 queries</p>
  
  <pre><code>json.array!(@some_records.includes(integrated_product: [company: [ logo_attachment: :blob ]])) do |one_record|
    product ||= one_record.integrated_product
    if !product.logo.attached?
      json.logo_img url_for(product.logo)
    elsif !product.company.logo.attached?
      json.logo_img url_for(product.company.logo)
    end
  </code></pre>
  
  <p>....</p>
  
  <p>Any thoughts on how to handle this in a proper way (preloading attachments &amp; avoiding n+1) are appreciated.</p>
  
  <p>Update:</p>
  
  <p>I want to have the whole collection that I passed, <em>including items <strong>with &amp; without</strong> attachment</em>, searching for a condition that will check if that already loaded item has an attachment or not to display an image if it has attachment</p>