使用Rails 4,Model.scoped是pcated德$ P $,但Model.all不能代替它 [英] With Rails 4, Model.scoped is deprecated but Model.all can't replace it

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

问题描述

开始轨道4, Model.scoped 现在是很precated。

Starting Rails 4, Model.scoped is now deprecated.

DE preCATION警告:Model.scoped是pcated德$ P $。请使用Model.all代替。

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

不过,有一个在 Model.scoped的差异 Model.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:

> 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

有在图书馆用例/担心返回范围时,有一个条件做某件事,或者什么都没有,像这样:

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

如果你想改变这个范围所有,你会遇到随机的问题,这取决于其中被用在作用域链。例如, Model.where。(一些:值).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 ::关联,仅仅返回一个范围。

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

我该怎么办吗?

推荐答案

看来,其中,(无)范围内的一个真正的替代,其中on Rails的是双向3和4:(

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

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

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