Rails 中的范围/named_scope 是什么?
我最近开始实习了。我的雇主在 Rails 上使用 ruby,我经常遇到需要查找才能理解的新语法。我在谷歌上搜索了对named_scope的很好的解释,但到目前为止我发现的大多是对它给予高度赞扬的博客文章,而不是直接的定义或介绍。
ruby on Rails 中的named_scope(现在简称为scope)到底是什么?
I've recently started an internship. My employer uses ruby on rails, and I frequently encounter new syntax that I need to look up to understand. I've googled around for a good explanation of named_scope, but what I've found so far is mostly blog posts giving high praise for it, rather a straight definition or introduction.
What exactly is named_scope (now simply called scope) in ruby on rails?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
范围是集合的子集。听起来很复杂?事实并非如此。想象一下:
您有用户。现在,其中一些用户已订阅您的时事通讯。您通过向用户数据库添加字段 (user.subscribed_to_newsletter = true) 来标记接收新闻通讯的用户。当然,您有时希望吸引那些订阅您的时事通讯的用户。
当然,你可以总是这样做:
但是,你可以做这样的事情,而不是总是写这个。
如果您使用的是 Rails 4 或更高版本,请改为执行此操作:
这允许您通过简单地执行以下操作来访问您的订阅者:
这是一个非常简单的示例,但在一般范围内可以是非常强大的工具,可以轻松你的工作。
查看此链接:API 说明
A scope is a subset of a collection. Sounds complicated? It isn't. Imagine this:
You have Users. Now, some of those Users are subscribed to your newsletter. You marked those who receive a newsletter by adding a field to the Users Database (user.subscribed_to_newsletter = true). Naturally, you sometimes want to get those Users who are subscribed to your newsletter.
You could, of course, always do this:
Instead of always writing this you could, however, do something like this.
If you're using Rails 4 or newer, do this instead:
This allows you to access your subscribers by simply doing this:
This is a very simple example but in general scopes can be very powerful tools to easy your work.
Check out this link: API Description
Active Record 中的作用域类似于类方法,但它们返回 Relation 对象,这意味着您可以在其上调用另一个作用域或活动记录查询方法。
例如,如果您有一个具有下面提到的作用域方法的 Zombie 模型(zombies 表),
并且您调用
它,它会在 SQL 中转换为以下内容,
上面的示例基于 Rails 4 语法
scope in active record is like class methods but they return Relation object which means you can call another scope or active record querying method on it.
For example, if you have a Zombie model (zombies table) with below mentioned scope methods,
And you call
It translates to the below in SQL,
Example above is based on rails 4 syntax
了解详细信息的最佳方法是访问 API 文档。
您将获得完整的详细信息以及我们使用范围的方法。
API 范围文档
The best way to understand about the details is to go to API Documentation.
You'll get the complete details and the ways we can use Scopes.
API Documentation of Scope
现在想象一下你:
您可以通过使用范围来获得那些特定类别的人!
现在这并不难,不是吗?
Now imagine you :
You could get those particular classes of people by using a scope!
Now that wasn't so hard was it?