Rails 4 默认范围 [英] Rails 4 default scope

查看:31
本文介绍了Rails 4 默认范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my Rails app have a default scope that looks like this:

default_scope order: 'external_updated_at DESC'

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

I have now upgraded to Rails 4 and, of course, I get the following deprecation warning "Calling #scope or #default_scope with a hash is deprecated. Please use a lambda containing a scope.". I have successfully converted my other scopes but I don't know what the syntax for default_scope should be. This doesn't work:

default_scope, -> { order: 'external_updated_at' }

推荐答案

应该是:

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

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

default_scope accept a block, lambda is necessary for scope(), because there are 2 parameters, name and block:

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

这篇关于Rails 4 默认范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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