【发布时间】:2013-08-13 00:47:50
【问题描述】:
从 Rails 4 开始,Model.scoped 现已弃用。
DEPRECATION WARNING: Model.scoped is deprecated. Please use Model.all instead.
但是,Model.scoped 和Model.all 有区别,即scoped.scoped 返回一个范围,而all.all 运行查询。
在 Rails 3 上:
> Model.scoped.scoped.is_a?(ActiveRecord::Relation)
=> true
在 Rails 4 上:
> Model.all.all.is_a?(ActiveRecord::Relation)
DEPRECATION WARNING: Relation#all is deprecated. If you want to eager-load a relation, you can call #load (e.g. `Post.where(published: true).load`). If you want to get an array of records from a relation, you can call #to_a (e.g. `Post.where(published: true).to_a`).
=> false
当有条件做某事或什么都不做时,库/关注点中有一些用例会返回scoped,如下所示:
module AmongConcern
extend ActiveSupport::Concern
module ClassMethods
def among(ids)
return scoped if ids.blank?
where(id: ids)
end
end
end
如果您将此scoped 更改为all,您将面临随机问题,具体取决于among 在作用域链中的使用位置。例如,Model.where(some: value).among(ids) 将运行查询而不是返回范围。
我想要的是ActiveRecord::Relation 上的幂等方法,它只返回一个范围。
我应该在这里做什么?
【问题讨论】:
-
你确定“
all运行查询”的东西不仅仅是控制台的产物吗? The source 建议它应该可以正常工作。 -
但是您没有收到该警告,因此您从
scoping/named.rb获得了all,对吗?scoping/named.rb中的all是,AFAIK,Model.all使用。
标签: activerecord ruby-on-rails-4