[英]ActiveRecord scope returns an array
I have a scope that returns an Array
instead of an ActiveRecord Relation
when it is called, but if I call the methods within the scope, it returns an ActiveRecord Relation
. 我有一个范围,在调用它时返回一个Array
而不是一个ActiveRecord Relation
,但如果我调用范围内的方法,它将返回一个ActiveRecord Relation
。
scope :beta_user, -> {
joins(:config).where("config_type = 'Model' AND opts #>> '{beta}' = 'true'")
}
# Calling scope directly
Model.beta_user # => [Model1, Model2, Model3]
Model.beta_user.class # => Array
# Calling scope definition
Model.joins(:config).where("config_type = 'Model' AND opts #>> '{beta}' = 'true'")
=> [Model1, Model2, Model3]
Model.joins(:config).where("config_type = 'Model' AND opts #>> '{beta}' = 'true'").class
=> Model::ActiveRecord_Relation
So my question here is, what's going on with the inconsistent return types? 所以我的问题是,不一致的返回类型会发生什么? I'm unable to chain other scopes after this (I can still chain them before it) and I can't use other AR Relation
methods such as #order
and #pluck
. 在此之后我无法链接其他范围(我仍然可以在它之前链接它们)并且我不能使用其他AR Relation
方法,例如#order
和#pluck
。
From what I can see in the console, it seems like calling Model.beta_user.class
is still executing the query whereas Model.joins(:config).where("config_type = 'Model' AND opts #>> '{beta}' = 'true'")
does not execute the query. 从我在控制台中可以看到,似乎调用Model.beta_user.class
仍在执行查询,而Model.joins(:config).where("config_type = 'Model' AND opts #>> '{beta}' = 'true'")
不执行查询。 I thought a scope was not supposed to execute until it needed to in order to optimize for chained scopes/queries. 我认为范围不应该执行,直到它需要为链式范围/查询进行优化。
A scope indeed returns a relation object, however it will convert it when necessary, when you run the scope in your console it will try to inspect it and will do the conversion. 范围确实返回一个关系对象,但是它会在必要时转换它,当你在控制台中运行范围时,它会尝试检查它并进行转换。
But try this, it should work: 但试试这个,它应该工作:
scope = Model.beta_user
# pluck should work
scope.pluck(:id)
And all the other methods like first
, last
, count
, all
, etc... should work 所有其他方法,如first
, last
, count
, all
等......应该可行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.