Ruby on rails Rails:使用eager_加载范围会产生错误
我正在做一个Ruby on rails Rails:使用eager_加载范围会产生错误,ruby-on-rails,rails-activerecord,Ruby On Rails,Rails Activerecord,我正在做一个Rails项目,并试图在我的模型中创建一个范围,而不是实例方法,并在需要时预加载该范围。但我不是很有经验的范围和有困难的工作,或可能是我做的一切都错了。我有一个实例方法做同样的事情,但注意到它有一些n+1的问题。我受到这篇文章的启发,想试试scopes (作为旁注,我使用的是祖先gem) 我尝试了三种不同的方法来创建范围。它们都适用于频道。通过(名称:“旅行”)查找。深度,但在频道中出错。包括(:深度)或急切加载 第一次尝试: 有_one:depth,->{parent?(paren
Rails
项目,并试图在我的模型中创建一个范围
,而不是实例方法
,并在需要时预加载该范围。但我不是很有经验的范围和有困难的工作,或可能是我做的一切都错了。我有一个实例方法做同样的事情,但注意到它有一些n+1的问题。我受到这篇文章的启发,想试试scopes
(作为旁注,我使用的是祖先
gem)
我尝试了三种不同的方法来创建范围。它们都适用于频道。通过(名称:“旅行”)查找。深度,但在频道中出错。包括(:深度)
或急切加载
第一次尝试:
有_one:depth,->{parent?(parent.depth+1):0},类名:“Channel”
第二次尝试:
有一个:depth,->(node){where(“id:=?”,node.parent?(node.parent.depth+1):0},类名:“Channel”
第三次尝试:
有一个:深度,->{where(“id:=channels.id”).parent?(parent.depth+1):0},类名:“Channel”
在控制台中,这三种功能均可正常工作:
Channel.find_by(name: "Travel").depth
Channel Load (0.4ms) SELECT "channels".* FROM "channels" WHERE "channels"."name" = $1 LIMIT $2 [["name", "Travel"], ["LIMIT", 1]]
=> 2
。但是
Channel.includes(:depth)
为每个范围(1、2、3)提供了三种不同的错误
第一个作用域的错误:
NameError (undefined local variable or method `parent' for #<Channel::ActiveRecord_Relation:0x00007fdf867832d8>)
第三个作用域的错误:
Object doesn't support #inspect
我做错了什么?或者,最好的方法是什么?感谢您的时间和帮助。我认为.depth
方法返回的是一个与记录无关的整数值。急切加载是加载模型返回的对象的关联记录的机制。使用尽可能少的查询查找
如果要加速深度
方法,需要启用:cache_depth
选项。根据祖先宝石文件:
:cache_depth
Cache the depth of each node in the 'ancestry_depth' column(default: false)
If you turn depth_caching on for an existing model:
- Migrate: add_column [table], :ancestry_depth, :integer, :default => 0
- Build cache: TreeNode.rebuild_depth_cache!
在您的模型中:
class [Model] < ActiveRecord::Base
has_ancestry, cache_depth: true
end
class[Model]
谢谢@Juan。我最终采取了一种不同的方法,没有使用深度。但是我想试试你的答案。
class [Model] < ActiveRecord::Base
has_ancestry, cache_depth: true
end