Rails 什么时候执行查询并加载到内存中? [英] When does Rails perform the query and loads into memory?

查看:43
本文介绍了Rails 什么时候执行查询并加载到内存中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个 User 表和 House 表,我这样做:

If I have a User table and House table and I do this:

users = User.where(status: 3)

homes = Home.joins(:user).merge(users)

在第一次分配时,我是否已经在执行查询?还是等到第二个才执行查询?还是在您实际尝试访问这些结果中的任何一个时执行此操作?Rails 如何知道何时执行查询?

On the first assignation am I performing a query already? Or it waits until the second to perform the query? Or it does it when you actually try to access any of those results? How does Rails manage to know when to perform the query?

推荐答案

where 方法返回一个 ActiveRecord::Relation 对象,并且该对象本身不会发出一个数据库查询.重要的是你在哪里使用这个对象.join 方法也使用关联表延迟加载数据库查询,但只将 Home 表加载到内存中,因为关联的 User 表是不需要.之后您有了 mergemerge 方法所做的是一种在连接模型上使用命名范围的简单方法.类似的东西

The where method returns an ActiveRecord::Relation object, and by itself this object does not issue a database query. It's where you use this object that matters. join method as well lazy loads the database query by utilising the associated table, but only loading the Home table into memory as the associated User table is not required. Afterwards you have merge, what merge method does is a simple way of using a named scope on a joined model. Something like

class Home < ActiveRecord::Base
  has_many :users
end

class User < ActiveRecord::Base
  belongs_to :home

  scope :available, ->{ where(available: true) }
end

这篇关于Rails 什么时候执行查询并加载到内存中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆