rails 中的 scope/named_scope 是什么? [英] What is scope/named_scope in rails?

查看:87
本文介绍了rails 中的 scope/named_scope 是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始实习.我的雇主使用 ruby​​ on rails,我经常遇到需要查找才能理解的新语法.我在谷歌上搜索了对 named_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.

ruby on rails 中的named_scope(现在简称为scope)到底是什么?

What exactly is named_scope (now simply called scope) in ruby on rails?

推荐答案

范围是集合的子集.听起来很复杂?不是.想象一下:

A scope is a subset of a collection. Sounds complicated? It isn't. Imagine this:

您有用户.现在,其中一些用户订阅了您的时事通讯.您通过向用户数据库添加一个字段来标记接收时事通讯的人 (user.subscribed_to_newsletter = true).当然,您有时希望让那些订阅您的时事通讯的用户.

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:

User.where(subscribed_to_newsletter: true).each do #something

然而,您可以做这样的事情,而不是总是写这个.

Instead of always writing this you could, however, do something like this.

#File: users.rb
class User < ActiveRecord::Base
  scope :newsletter, where(subscribed_to_newsletter: true)
  #yada yada
end

如果您使用的是 Rails 4 或更新版本,请改为:

If you're using Rails 4 or newer, do this instead:

#File: users.rb
class User < ActiveRecord::Base
  scope :newsletter, -> { where(subscribed_to_newsletter: true) }
  #yada yada
end

这让您只需执行以下操作即可访问您的订阅者:

This allows you to access your subscribers by simply doing this:

User.newsletter.each do #something

这是一个非常简单的示例,但总的来说,范围可以成为简化您工作的非常强大的工具.

This is a very simple example but in general scopes can be very powerful tools to easy your work.

查看此链接:API 说明

这篇关于rails 中的 scope/named_scope 是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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