【问题标题】:How do I make an ActiveRecord scope that doesn't affect the query in Rails 3 using Arel (presumably)?如何使用 Arel(大概)创建一个不影响 Rails 3 中的查询的 ActiveRecord 范围?
【发布时间】:2011-11-12 10:39:59
【问题描述】:

基本上我正在寻找一种无操作类型的关系来应用于一系列范围。

假设我有一个范围链:

Post.approved.published.all

现在,出于调试目的,我希望让 published 范围什么都不做,这样链就只会返回 approved 帖子,无论它们是否为 published

我会在以下方法中返回什么:

def self.published
  # what to return?
end

【问题讨论】:

    标签: ruby-on-rails-3 activerecord arel scopes


    【解决方案1】:

    published 设为all 的别名,或使用scoped 来返回可以链接附加条件的关系:

    def self.published
      all
      #or
      scoped
    end
    

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

    scope :published, all
    

    或者,将其设为scoped 的别名:

    scope :published, scoped
    

    【讨论】:

    • 我确实在寻找所有的东西,现在它是如此明显,我不知道为什么我没有想到这一点。
    • 这确实很旧,但是如果您想要关系而不是数组,请使用 scoped 返回匿名范围(Rails 3)。
    • @kardeiz 是的,这绝对是更好的方法,我在写这个答案时没有意识到。
    • 现在在 Rails 4 中你不应该再使用scoped,而是回到all。 :) all 现在返回一个关系。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-30
    • 1970-01-01
    • 2012-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多