rails 中的作用域和作用域 [英] Scoped and scope in rails

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

问题描述

有人能解释一下这个方法的作用以及我可以传递给它什么吗?

Can somebody explain what this method does and what I can pass to it?

scoped(options = nil)
Returns an anonymous scope.

还有作用域方法有什么作用?阅读文档后我不明白.

And also what the scope method does? I don't understand after reading the documentation.

推荐答案

在 ActiveRecord 中,所有查询构建方法(如whereorderjoinslimit 等)返回一个所谓的 scope.只有当您调用像 allfirst 这样的 kicker 方法时,才会执行构建的查询并返回数据库中的结果.

In ActiveRecord, all query building methods (like where, order, joins, limit and so forth) return a so called scope. Only when you call a kicker method like all or first the built-up query is executed and the results from the database are returned.

scoped 类方法也返回一个范围.返回的范围默认为空,这意味着不会以任何方式限制结果集,这意味着如果执行查询,将返回所有记录.您可以使用它来提供一个空"的替代方案,就像 MurifoX 的 query_by_date 示例一样.或者,您可以使用它将多个条件组合到一个方法调用中,例如:

The scoped class method also returns a scope. The scope returned is by default empty meaning the result set would not be restricted in any way meaning all records would be returned if the query was executed. You can use it to provide an "empty" alternative like in the query_by_date example by MurifoX. Or you can use it to combine multiple conditions into one method call, like for example:

Model.scoped(:conditions => 'id < 100', :limit => 10, :order => 'title ASC')

# which would be equivalent to
Model.where('id < 100').limit(10).order('title ASC')

scope 类方法允许你定义一个也返回一个范围的类方法,例如:

The scope class method allows you to define a class method that also returns a scope, like for example:

class Model
  scope :colored, lambda {|col|
    where(:color => col)
  }
end

可以这样使用:

Model.colored

作用域的好处是您可以(几乎)随意组合它们,因此绝对有可能:

The nice thing with scopes is that you can combine them (almost) as you wish, so the following is absolutely possible:

Model.red.where('id < 100').order('title ASC').scoped(:limit => 10)

我还强烈建议通读http://guides.rubyonrails.org/active_record_querying.html

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

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