如何使用Arel(大概)创建一个不影响Rails 3中查询的ActiveRecord范围?

jak*_*ils 15 activerecord arel scopes ruby-on-rails-3

基本上我正在寻找一种适用于范围链的无操作类型的关系.

可以说我有一系列范围:

Post.approved.published.all
Run Code Online (Sandbox Code Playgroud)

现在,出于调试目的,我希望published范围根本不做任何事情,因此链只会返回approved帖子,无论它们是否published存在.

我将通过以下方法返回什么:

def self.published
  # what to return?
end
Run Code Online (Sandbox Code Playgroud)

mea*_*gar 19

published一个别名all,或使用scoped返回到可chainged附加条件的关系:

def self.published
  all
  #or
  scoped
end
Run Code Online (Sandbox Code Playgroud)

我会使用范围,返回all...

scope :published, all
Run Code Online (Sandbox Code Playgroud)

或者,使其成为别名scoped:

scope :published, scoped
Run Code Online (Sandbox Code Playgroud)

  • 现在在Rails 4中你不应该再使用`scoped`了,而是回到`all`.:)`all`现在返回一个关系. (8认同)
  • 这真的很旧,但是如果你想要Relation而不是数组,那么使用`scoped`来返回一个匿名范围(Rails 3). (2认同)