在我的应用中,帖子有很多标签。
标签通过连接表 join_tags 连接
在我列出所有帖子的索引 View 中,我会这样做:
<% post.tags.each do |tag| %>
<%= tag.name %>,
<% end %>
这里的问题是它会为每个帖子访问数据库以加载标签。
有没有办法在 Controller 中一次加载这些任务的所有标签?也许通过@Posts var?我有一种预加载的感觉?
最佳答案
是的,你可以,正如你所说,eager loading是实现此目的的正确方法,您可能希望在 Controller 操作中执行类似的操作:
def index
@posts = Post.includes(:tags).all
end
假设您的帖子模型中有以下关系:
has_many :join_tags
has_many :tags, :through => :join_tags
它将为您节省 n+1 次标签后查询。
关于ruby-on-rails - 在 rails 3 中预先加载 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6118362/