0

I'm using attachinary gem (1.3.0) to manage files in my rails 3 application. Assume that attachinary is bind to a model Business like

class Business < ActiveRecord::Base
  has_attachment :logo
end

On a page I'm rendering ~30 business instances, and while optimizing my app, I've noticed that for every business.logo call new database query is made, so ~30 extra queries are made for each logo. When I've tried to include logo in a businesses query, it failed because logo is not actually a relation.

Business.includes(:logo) # failed

How do I include attachinary as a relation to a query?

Michael Radionov
  • 12,859
  • 1
  • 55
  • 72

1 Answers1

1

attachinary internally defines a relation, and then just wraps it to human readable has_attachment and has_attachments. what it actually does is (code is here):

relation = "#{options[:singular]}_files"

so you can access original relation with logo_files and add it to query like:

Business.includes(:logo_files)

no extra queries will be made, all entries will be joined to a query. from instance it will still be accessible as logo:

business.logo
Michael Radionov
  • 12,859
  • 1
  • 55
  • 72
  • self-answered question in less than a minute? Are you trygin to get more reputation? Ahah – MrYoshiji May 26 '14 at 20:49
  • 1
    @MrYoshiji, not at all. I was unable to find answer to this question all over the internet, so I've decided to share the solution if somebody will be looking for it later to save their time, so I've posted q+a at one time.+ it does not seem to be a very popular problem that will gain my rep significantly – Michael Radionov May 27 '14 at 09:19