Rails 3 中的控制器中的预加载
在我的应用程序中,帖子有很多标签。
标签通过连接表 join_tags 连接。
在我的索引视图中,列出了所有帖子,我做了如下操作:
<% post.tags.each do |tag| %>
<%= tag.name %>,
<% end %>
这里的问题是,它会为每个帖子访问数据库来加载标签。
有没有办法在控制器中加载这些任务的所有标签?也许通过@Posts var?我有一种感觉是通过急切加载?
In my app, posts has many tags.
the tags are connected through a join table, join_tags
In my index view, which lists all the posts, I do something like so:
<% post.tags.each do |tag| %>
<%= tag.name %>,
<% end %>
The problem here, is its hitting the database for each post to load the tags.
Is there a way to load all of the tags for these tasks once in the controller? Maybe through the @Posts var? I have a feeling its through eager loading?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,你可以,正如你所说,急切加载是正确的方法为了实现这一点,您可能需要在控制器操作中执行类似的操作:
假设您的帖子模型中有以下关系:
它将为您节省 n+1 个帖子标签查询。
Yes you can, and as you said, eager loading is the right way to achieve this, you may want to do something like this in your controller action:
Assuming you have the following relationships in your post model:
It will save you the n+1 post-tag queries.
查看您的控制器代码会很有帮助,但我认为您正在寻找类似的内容:
It would be helpful to see your controller code, but I think you're looking for something like: