ruby-on-rails-4thinking-sphinxeager-loading

Loading data from associated model in same query in rails


Basically, I have a Listing model, where each listing has a country id. I need the country name in my search results view. I know I can do @listing.country.name, but this performs an extra query for each listing in my search results. I'm using Thinking Sphinx, and in my controller I have

@listings = Listing.search(@ts_params).page(page_num).per(limit) 

I have tried adding .includes(:countries) and variations thereof but no luck.

What's the best way to go about this? I want the country data to be fetched in the same query as the listings.

I have exactly the same issue with listing images - it is performing an extra query for every listing to find the image, when surely it can be done in one with joins.


Solution

  • Are you trying to eager load the associated model (to avoid an N + 1 query problem), or are you trying to load the associated model into fields on the parent model?

    If it's the former, you're probably better off forgetting about :select and instead of :joins using:

    ts_params[:sql][:include] = :countries, :listing_images
    

    Now you should be able to call listing.countries and listing.listing_images to access child models, as normal.