使用 Rails 4,不推荐使用 Model.scoped 但 Model.all 不能替换它 [英] With Rails 4, Model.scoped is deprecated but Model.all can't replace it

查看:26
本文介绍了使用 Rails 4,不推荐使用 Model.scoped 但 Model.all 不能替换它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从 Rails 4 开始,Model.scoped 现已弃用.

Starting Rails 4, Model.scoped is now deprecated.

<代码>弃用警告:不推荐使用 Model.scoped.请改用 Model.all.

但是,Model.scopedModel.all 是有区别的,即 scoped.scoped 返回一个范围,而 all.all 运行查询.

But, there's a difference inModel.scoped and Model.all, that is, scoped.scoped returns a scope, while all.all runs the query.

在 Rails 3 上:

On Rails 3:

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

在 Rails 4 上:

On 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,如下所示:

There are use cases in libraries / concerns that returns scoped when there's a conditional to do something or nothing, like so:

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) 将运行查询而不是返回范围.

If you'd change this scoped to all, you'd face random problems depending where the among was used in the scope chain. For instance, Model.where(some: value).among(ids) would run the query instead of returning a scope.

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

What I want is an idempotent method on ActiveRecord::Relation that simply returns a scope.

我应该在这里做什么?

推荐答案

看来 where(nil)scoped 的真正替代品,它同时适用于 Rails3 和 4.:(

It seems that where(nil) is a real replacement of scoped, which works both on Rails 3 and 4. :(

这篇关于使用 Rails 4,不推荐使用 Model.scoped 但 Model.all 不能替换它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆