Rails即时加载,但不加载嵌套关联记录



我有以下三个类

Class User < ActiveRecord
has_many :addresses
end
Class Address < ActiveRecord
belongs_to :country
end
Class Country < ActiveRecord
has_many :addresses
end

我试图通过以下命令急切加载所有嵌套的关联记录

User.includes(addresses: :country)但是在rails控制台中,只有User和address被加载,而不是国家。我不知道我错过了什么。

你需要使用散列来声明嵌套资源的即时加载,例如

User.includes(addresses: [:country])

不是

User.includes(addresses: :country)

参见docs

下面是一个完整的工作示例(Rails 6)

class Person < ApplicationRecord
has_many :projects
end
class Company
has_many :projects
end
class Project < ApplicationRecord
belongs_to :person
belongs_to :company
end

然后,在控制台上:

ActiveRecord::Base.logger = Logger.new(STDOUT)
me = Person.includes(projects: [:company]).find 4
Person Load (0.3ms)  SELECT "people".* FROM "people" WHERE "people"."id" = $1 LIMIT $2  [["id", 4], ["LIMIT", 1]]
Project Load (0.4ms)  SELECT "projects".* FROM "projects" WHERE "projects"."person_id" = $1  [["person_id", 4]]
Company Load (0.5ms)  SELECT "companies".* FROM "companies" WHERE "companies"."id" IN ($1, $2, $3, $4, $5 ...)
me.projects.first.company.name
=> "my first project's customer name"

请注意,在请求我的第一个项目的客户名称和生成返回值之间没有对数据库的查询。如果有,则该查询将由记录器打印,该记录器将其输出到STDOUT

相关内容

  • 没有找到相关文章

最新更新