gpt4 book ai didi

sql - Rails 有 activerecord 一次性获取所有需要的关联吗?

转载 作者:行者123 更新时间:2023-11-29 12:31:45 25 4
gpt4 key购买 nike

我有一个评论模型,它有一个用户。

在我的显示页面中,我正在执行 Comment.all,然后显示每条评论。

在 View 中,我不仅需要显示评论,还需要显示有关关联用户(即作者)的信息。

<% @comments.each do |comment| %>
<%= comment.user.name %>
<%= comment.user.email %>
...etc...
<% end %>

一切都很好,但 activerecord 将其转换为一个 SELECT * FROM users WHERE USER.id = commentId 查询每个我有的评论。

这有点荒谬,尤其是在一个有数百条评论的页面上。 (这是数百个单独的数据库命中!)

当我执行 Comment.all 时,是否可以告诉 rails 不仅要抓取评论,还要抓取关联的用户,然后当我稍后调用 comment.user.blah 时,让它不要抓取它再次从数据库? (这样它将在一个数据库语句中完成所有操作)。

最佳答案

你应该使用.includes

来自doc :

Solution to N + 1 queries problem

Active Record lets you specify in advance all the associations that are going to be loaded. This is possible by specifying the includes method of the Model.find call. With includes, Active Record ensures that all of the specified associations are loaded using the minimum possible number of queries.

Revisiting the above case, we could rewrite Client.all to use eager load addresses:

clients = Client.includes(:address).limit(10)

clients.each do |client|
puts client.address.postcode
end

或者,在你的情况下,它会是

Comment.includes(:user)

关于sql - Rails 有 activerecord 一次性获取所有需要的关联吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8722632/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com