gpt4 book ai didi

ruby-on-rails-3 - Rails3 : Avoiding select n+1 with the Ancestry Gem?

转载 作者:行者123 更新时间:2023-12-01 10:09:28 28 4
gpt4 key购买 nike

要求:

我正在构建一个任务列表应用程序,并希望任务能够具有子任务。
我还希望任务能够同时存在于树中的多个位置,例如,如果我有 2 个任务:

  1. build 狗窝
  2. 竖起新栅栏

如果我打算用与栅栏相同的 Material build 狗窝,这两个任务都会有一个子任务“购买栅栏板”。

我有问题的实现(欢迎反馈):

我有 2 个模型:

  • 节点(has_ancestry 和 belongs_to :task)
  • 任务(has_many :nodes)

这意味着树(允许我拥有子任务)不存储它自己的任务,只是对任务对象的引用。

这是一个使用 rails 控制台的示例:

t1 = Task.create :name => "Build dog kennel"
n1 = Node.create :task => t1

t2 = Task.create :name => "Put up new fence"
n2 = Node.create :task => t2

t3 = Task.create :name => "Buy fence palings"
n11 = Node.create :task => t3, :parent => n1
n21 = Node.create :task => t3, :parent => n2

t4 = Task.create :name => "Construct the fence"
n22 = Node.create :task => t4, :parent => n2

n2.children.each { |c| puts c.task.name }

最后一行给出以下输出,表示选择 n+1:

Node Load (0.2ms)  SELECT "nodes".* FROM "nodes" WHERE "nodes"."ancestry" = '12'
Task Load (0.2ms) SELECT "tasks".* FROM "tasks" WHERE "tasks"."id" = 11 LIMIT 1
Buy fence palings
Task Load (0.2ms) SELECT "tasks".* FROM "tasks" WHERE "tasks"."id" = 10 LIMIT 1
Put up new fence

帮助?

我对 Ruby on Rails 和 ActiveRecord 还很陌生,但我认为我需要做的就是根据 nodes.task_id 外键将节点表与任务表连接起来,但我已经查看了 Ancestry documentation 和找不到有用的东西。

将来我还计划通过外键从任务对象中获取更多信息,例如作者、相关评论等。通过这种实现,一个页面加载可能会触发相当多的选择查询:(

任何人都可以就如何实现这一点向我提供建议吗?
有没有办法强制急切加载? (有帮助吗?)
如果您对如何完成此操作有更好的想法,我愿意提供反馈。

提前致谢!

最佳答案

所以在玩了一段时间后,我终于找到了一种方法。

代替这一行:

n2.children.each { |c| puts c.task.name }

结果如下:

Node Load (0.2ms)  SELECT "nodes".* FROM "nodes" WHERE "nodes"."ancestry" = '27'
Task Load (0.2ms) SELECT "tasks".* FROM "tasks" WHERE "tasks"."id" = 23 LIMIT 1
Buy fence palings
Task Load (0.2ms) SELECT "tasks".* FROM "tasks" WHERE "tasks"."id" = 24 LIMIT 1
Construct the fence

我用了这条线:

n2.children.find(:all, :include => :task).each { |c| puts c.task.name }

这导致了:

Node Load (0.2ms)  SELECT "nodes".* FROM "nodes" WHERE "nodes"."ancestry" = '27'
Task Load (0.2ms) SELECT "tasks".* FROM "tasks" WHERE "tasks"."id" IN (23, 24)
Buy fence palings
Construct the fence

这应该只执行 2 个查询,无论大小如何,结果集都将包括任务!
我知道这可能是基本的东西,但对于像我这样的新人来说可能有点困惑,因为 section of the rails guides that refers to eager loading只显示类方法 includes()

关于ruby-on-rails-3 - Rails3 : Avoiding select n+1 with the Ancestry Gem?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6955779/

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