Rails 4默认作用域

在我的 Rails 应用程序中有一个默认的作用域,看起来像这样:

default_scope order: 'external_updated_at DESC'

我现在已经升级到 Rails 4,当然,我得到了以下不推荐的警告: “使用散列调用 # scope 或 # default _ scope 是不推荐的。请使用一个包含范围的 lambda。”.我已经成功地转换了其他作用域,但是我不知道 default _ scope 的语法应该是什么。这样行不通:

default_scope, -> { order: 'external_updated_at' }
53854 次浏览

应该只有:

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

Default _ scope 接受一个块,scope ()需要 lambda,因为有两个参数,name 和 block:

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

这就是对我有效的方法:

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

这对我也有效:

default_scope { order('created_at DESC') }

这对我有用(只是为了说明在哪里) ,因为我来到这个主题通过同样的问题。

default_scope { where(form: "WorkExperience") }

这在 Rails 4中对我很有用

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

别忘了 ->符号

default_scope {
where(published: true)
}

试试这个。

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

default_scope lambda {
order(external_updated_at: :desc)
}

相当于

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

还有

default_scope { order(external_updated_at: :desc) }