在 Rails 4 中,Model.scoped 已被弃用,但 Model.all 无法替代它

2023-11-29

启动《轨道 4》,Model.scoped现已弃用。

DEPRECATION WARNING: Model.scoped is deprecated. Please use Model.all instead.

但是,有一个区别Model.scoped and Model.all, 那是,scoped.scoped返回一个范围,同时all.all运行查询。

铁轨3:

> Model.scoped.scoped.is_a?(ActiveRecord::Relation)
=> true

轨道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 to all,你会面临随机问题,具体取决于among在作用域链中使用。例如,Model.where(some: value).among(ids)将运行查询而不是返回范围。

我想要的是幂等方法ActiveRecord::Relation它只是返回一个范围。

我应该在这里做什么?


看起来where(nil)是真正的替代品scoped,适用于 Rails 3 和 4。:(

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Rails 4 中,Model.scoped 已被弃用,但 Model.all 无法替代它 的相关文章

随机推荐