向作用域添加参数 [英] Adding parameter to a scope

查看:26
本文介绍了向作用域添加参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ActiveRecord 查询,例如:

I have a ActiveRecord query for example like this:

@result = stuff.limit(10)

where stuff 是带有 where 子句、order by 等的活动记录查询...

where stuff is a active record query with where clauses, order by, etc...

现在我想为什么要向控制器传递这样的幻数?那么你认为为limit(10)"定义一个范围并使用它是一个好习惯吗?以及语法是什么样的?

Now I thought why to pass magic numbers like that to the controller? So do you think is it a good practice to define a scope for "limit(10)" and use that instead? and how would the syntax look like?

推荐答案

范围看起来像任何其他范围(尽管您可能更喜欢类方法),例如,

The scope would look like any other (although you may prefer a class method), e.g.,

class Stuff < ActiveRecord::Base
  def self.lim
    limit(3)
  end
end

> Stuff.lim.all
=> [#<Stuff id: 1, name: "foo", created_at: "2013-03-01 17:58:32", updated_at: "2013-03-01 17:58:32">,
 #<Stuff id: 2, name: "bnar", created_at: "2013-03-01 17:58:32", updated_at: "2013-03-01 17:58:32">,
 #<Stuff id: 3, name: "baz", created_at: "2013-03-01 17:58:32", updated_at: "2013-03-01 17:58:32">]
> Stuff.all.length
=> 8

如果您总是(或几乎"总是)需要该限制,请使用默认范围:

If you always (or "almost" always) want that limit, use a default scope:

class Stuff < ActiveRecord::Base
  attr_accessible :name, :hdfs_file

  default_scope limit(3)
end

> Stuff.all
=> [#<Stuff id: 1, name: "foo", created_at: "2013-03-01 17:58:32", updated_at: "2013-03-01 17:58:32">,
 #<Stuff id: 2, name: "bnar", created_at: "2013-03-01 17:58:32", updated_at: "2013-03-01 17:58:32">,
 #<Stuff id: 3, name: "baz", created_at: "2013-03-01 17:58:32", updated_at: "2013-03-01 17:58:32">]
> Stuff.all.length
=> 3

要跳过默认范围:

> Stuff.unscoped.all.size
=> 8

这篇关于向作用域添加参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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