避免 Rails 中的 N+1 查询

Avoid N+1 Queries in Rails

提问人:jansha 提问时间:7/4/2023 更新时间:7/4/2023 访问量:43

问:

如何预先加载数据

我有三个模型,分别是城市、用户、银行

所以我需要急于加载数据以避免 N+1 查询

在我的 city.rb 方法中

def update_data(activity = false) # 用于延迟作业 # 过滤用户

#here i need to filter the users based on the activity

#if the activity is true then i need to fetch all the users of the city
else i need to fetch the users who belongs to the city where the bank of the user has enabled_banking flag false and those user who dont have any bank

so i have written a query like 



 filtered_users = activity ? users : users.left_joins(:banks).where("(banks.enabled_banking = ?) OR (banks.id IS NULL)", false)   

#then

filtered_users.find_in_batches do |city_users|
  city_users.each do |user|
    user.format_and_process
  end
end

结束

但是在这两种情况下,我都需要避免 n+1 查询,获取所有用户,以及当我附加左联接以获取记录时。

如何实现这一点

以前我更新了喜欢

users.includes(:city, :bank)

然后

 filtered_users = activity ? users : users.left_joins(:banks).where("(banks.enabled_banking = ?) OR (banks.id IS NULL)", false).references(:banks)
but this will not the optimzed way to fetch the records.


How we can achieve this expected behaviour?  
Ruby-on-Rails Ruby-on-Rails-4

评论

1赞 kwerle 7/5/2023
filtered_users.includes 应该这样做。也许在票证中包括实际发生的提取。我通常使用 github.com/flyerhzm/bullet 来调查这些 - 它做得很好。

答: 暂无答案