Loading data from associated model in same query in rails

那年仲夏 提交于 2019-12-06 00:52:23

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.

Thinking Sphinx provides functionality to eager load associated entities, so for eager loading we don't need to add [:sql]. Following is the way to do this.
For eager loading associated entities using sphinx.

ts_params[:include] = [:country, :listing_image]

I managed to solve this using the :sql hash provided by Thinking Sphinx. I now have the following:

@ts_params[:sql][:joins] = "INNER JOIN countries ON countries.id = listings.country_id INNER JOIN listing_images ON listing_images.listing_id = listings.id"
@ts_params[:sql][:select] = "listings.*, countries.name as country_name, listing_images.image as image_name"

This is correctly retrieving the country name and image name, but I still have a bit of work to do in making it work with the images - I think that will deserve its own question!

Current v4 syntax is:

Article.search :sql => {:include => :user}

Ref: https://freelancing-gods.com/thinking-sphinx/v4/searching.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!