【问题标题】:Rails 4 default scopeRails 4 默认范围
【发布时间】:2013-08-29 08:39:01
【问题描述】:

在我的 Rails 应用中,默认范围如下所示:

default_scope order: 'external_updated_at DESC'

我现在已经升级到 Rails 4,当然,我收到以下弃用警告“不推荐使用带有哈希的 #scope 或 #default_scope。请使用包含范围的 lambda。”。我已经成功地转换了我的其他范围,但我不知道 default_scope 的语法应该是什么。这不起作用:

default_scope, -> { order: 'external_updated_at' }

【问题讨论】:

标签: ruby-on-rails-4 default-scope


【解决方案1】:

应该只是:

class Ticket < ActiveRecord::Base
  default_scope -> { order(:external_updated_at) } 
end

default_scope 接受一个块,对于 scope() 需要 lambda,因为有 2 个参数,名称和块:

class Shirt < ActiveRecord::Base
  scope :red, -> { where(color: 'red') }
end

【讨论】:

  • 感谢卢克的解释。我遇到语法错误,然后我将其更改为 default_scope { order('external_updated_at') } 并且它有效。请您编辑您的答案,以便我接受吗?
  • 这在没有箭头的 4.0.2 中对我不起作用。我的工作解决方案是default_scope -&gt; { order_by(:created_at =&gt; :desc) }
  • 按照惯例,引用属性时首选符号。 default_scope { order(:external_updated_at) }
  • 顺便说一句,@JoeGatt 问题的正确答案是default_scope order('external_updated_at DESC')
  • 如果您有不同大小写的结果(大写与小写),这不解决排序问题...在强制小写时通过 default_scope 排序有什么想法吗?
【解决方案2】:

这对我有用:

default_scope  { order(:created_at => :desc) }

【讨论】:

  • 在新的 Ruby 语法中:default_scope { order(created_at: :desc) }
【解决方案3】:

这也对我有用:

default_scope { order('created_at DESC') }

【讨论】:

    【解决方案4】:

    这对我有用(只是为了说明一个地方),因为我是通过同样的问题来讨论这个话题的。

    default_scope { where(form: "WorkExperience") }
    

    【讨论】:

      【解决方案5】:

      您也可以使用lambda 关键字。这对于多行块很有用。

      default_scope lambda {
        order(external_updated_at: :desc)
      }
      

      相当于

      default_scope -> { order(external_updated_at: :desc) }
      

      default_scope { order(external_updated_at: :desc) }
      

      【讨论】:

        【解决方案6】:

        这在 Rails 4 中适用于我

        default_scope { order(external_updated_at: :desc) }
        

        【讨论】:

          【解决方案7】:
          default_scope -> { order(created_at: :desc) }
          

          别忘了-&gt; 符号

          【讨论】:

            【解决方案8】:
            default_scope { 
                  where(published: true) 
            }
            

            试试这个。

            【讨论】:

              猜你喜欢
              • 2011-09-02
              • 1970-01-01
              • 2014-01-30
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2016-07-11
              相关资源
              最近更新 更多