本文介绍了在Rails的同一查询中从关联模型加载数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我有一个列表模型,其中每个列表都有一个国家/地区ID。我的搜索结果视图中需要国家名称。我知道我可以执行 @ listing.country.name ,但这会对搜索结果中的每个列表执行一个额外的查询。我使用的是Think Sphinx,在我的控制器中,

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) 

我尝试添加 .includes(:国家/地区)及其变体,但没有运气。

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.

推荐答案

您是否要尝试加载关联的模型(以避免N + 1查询问题),还是您要尝试将关联的模型加载到父模型的字段中?

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?

如果是前者,则说明最好忘掉:select ,而不要使用以下命令而不是:joins

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

现在,您应该可以调用 listing.countries listing.listing_images 进行访问子模型,像往常一样。

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

这篇关于在Rails的同一查询中从关联模型加载数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 08:34