Rails 预加载问题 Find(:all, :include => [:model])
我有一个主题和一个项目模型。我在他们之间有一个多对多的屁股(HABTM)。
在主题的索引页中,我想显示每个主题拥有的项目数量。所以我的控制器里有
@topics = Topic.all(:include => [:projects])
,到目前为止一切都很好。问题是项目模型太大,查询仍然很慢
Topic Load (1.5ms) SELECT * FROM "topics"
Project Load (109.2ms) SELECT "projects".*, t0.topic_id as the_parent_record_id FROM "projects" INNER JOIN "projects_topics" t0 ON "projects".id = t0.project_id WHERE (t0.topic_id IN (1,2,3,4,5,6,7,8,9,10,11))
有没有办法让第二个查询不选择*而只选择名称或ID?因为HABTM Ass不支持counter_cache,而且我真的不想自己实现它......那么有没有办法让第二个查询更快?
我只需要拉动计数而不加载整个项目对象...
提前致谢,
Nicolás Hock Isaza
I have a Topic and a Project model. I have a Many-to-many ass between them (HABTM one).
In the Topic's Index Page, I want to display the number of projects that each topic have. So I have
@topics = Topic.all(:include => [:projects])
In my controller, and so far so good. The problem is that the Project Model is so big that the query is still really slow
Topic Load (1.5ms) SELECT * FROM "topics"
Project Load (109.2ms) SELECT "projects".*, t0.topic_id as the_parent_record_id FROM "projects" INNER JOIN "projects_topics" t0 ON "projects".id = t0.project_id WHERE (t0.topic_id IN (1,2,3,4,5,6,7,8,9,10,11))
Is there a way to make the second query not to select * but just the name or the ID? Because the counter_cache is not supported by the HABTM Ass, and I don't really want to implement it by myself... so is there a way to make this second query faster?
I just need to pull the count without loading the whole project object...
Thanks in advance,
Nicolás Hock Isaza
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
第二个选项是最好的 IMO,我通常根本不使用 habtm,只使用 double has_many :)
The second option is the best IMO, I usually don't use habtm at all, only double has_many :)
要扩展 Devenv 的答案 计数器缓存 是您通常使用的这种场景。
来自 API 文档:
这里是 ryan bates railscasts 位于 counter_cache 上。
此处 是我半年前提出的一个问题的答案,其中的解决方案是一个易于实现的自制计数器缓存。
To expand on Devenv's answer counter cache is what you would typically use for this kind of scenario.
From the api docs:
Here is a screen cast from ryan bates' railscasts on counter_cache.
Here is an answer to a question I asked half a year ago where the solution was an easily implemented home-brew counter cache.