首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails 5中数据库查询的优化

Rails 5中数据库查询的优化
EN

Stack Overflow用户
提问于 2022-05-09 20:00:41
回答 1查看 47关注 0票数 1

我有四个模特

代码语言:javascript
复制
module Vehicle
  has_many :routes
end

module Route
  has_many :route_users
  belongs_to :vehicle
end

module RouteUser
  belongs_to :route
  belongs_to :user
end

module User
  belongs_to :route_user
end

我的目标是通过user返回最新的驱动程序(一个aggregate.rb);具体来说,我需要用户id, first_name, last_name

代码语言:javascript
复制
  attributes = {
    id: vehicle.id,
    ... other attributes ...
  }

  attributes.merge!(
    driver: {
      id: vehicle.routes.last.route_users.last.user.id,
      first_name: vehicle.routes.last.route_users.last.user.first_name,
      last_name: vehicle.routes.last.route_users.last.user.last_name
    }
  ) if vehicle.routes.present? && vehicle.routes.last.route_users.present?

如您所见,.merge!加载了大量信息,大大减缓了aggregate.rb的返回速度。有任何方法来优化这个回报使它更快吗?我是不是遗漏了什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-05-10 02:12:59

您可以改进用户模型以使查询更容易。

代码语言:javascript
复制
class User < ApplicationRecord
  has_many :route_users
  has_many :routes, through: :route_users
  has_many :vehicles, through: :routes
end

当查询从一个侧面很大时,最好的方法是两个反转逻辑,然后从用户进行查询,例如:

首先获取last_user_drive,然后使用他的字段合并成属性

代码语言:javascript
复制
last_user_driver = User.joins(routes: :vehicle).where(vehicle: {id: vehicle.id}).order('routes.created_at').last

...
attributes.merge!(
  driver: {
    id: last_user_driver.id,
    first_name: last_user_driver.first_name,
    last_name: last_user_driver.last_name
  }
) if last_user_driver.present?
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72177609

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档