Zig*_*ggy 100 named-scope ruby-on-rails
我最近开始实习.我的雇主在轨道上使用ruby,我经常遇到我需要了解的新语法.我已经google了解了对named_scope的一个很好的解释,但到目前为止我发现的主要是博客文章,对它给予高度赞扬,而不是直接的定义或介绍.
在rails上的ruby中究竟是named_scope(现在简称为scope)?
小智 200
范围是集合的子集.听起来很复杂?事实并非如此.想象一下:
你有用户.现在,其中一些用户订阅了您的简报.您通过向用户数据库添加字段(user.subscribed_to_newsletter = true)来标记收到新闻稿的人.当然,您有时希望获得订阅您的简报的用户.
当然,你可以这样做:
User.where(subscribed_to_newsletter: true).each do #something
Run Code Online (Sandbox Code Playgroud)
但是,你可以做这样的事情而不是总是写这个.
#File: users.rb
class User < ActiveRecord::Base
scope :newsletter, where(subscribed_to_newsletter: true)
#yada yada
end
Run Code Online (Sandbox Code Playgroud)
如果您使用的是Rails 4或更高版本,请执行以下操作:
#File: users.rb
class User < ActiveRecord::Base
scope :newsletter, -> { where(subscribed_to_newsletter: true) }
#yada yada
end
Run Code Online (Sandbox Code Playgroud)
这允许您通过简单地执行此操作来访问您的订阅者:
User.newsletter.each do #something
Run Code Online (Sandbox Code Playgroud)
这是一个非常简单的示例,但通常范围可以是非常强大的工具,以方便您的工作.
查看此链接:API说明
小智 32
活动记录中的作用域类似于类方法,但它们返回Relation对象,这意味着您可以在其上调用另一个作用域或活动记录查询方法.
例如,如果你有一个带有下面提到的范围方法的Zombie模型(僵尸表),
class Zombie
scope :rotting, -> { where(rotting: true) }
scope :fresh, -> { where('age < ?', 25) }
scope :recent, -> { order(created_at: :desc) }
end
Run Code Online (Sandbox Code Playgroud)
你打电话
Zombie.rotting.fresh.recent.limit(3)
Run Code Online (Sandbox Code Playgroud)
它转换为SQL中的以下内容,
select "zombies.*" from "zombies" where "zombies"."rotting" = 't' and (age<20) order by create_at desc limit 3
Run Code Online (Sandbox Code Playgroud)
上面的示例基于rails 4语法
范围不过是类方法。
为什么要使用它们?
作用域设置使您可以指定常用查询(对于长期或最常用的查询,可以将其视为快捷方式),可以将其引用为关联对象或模型上的方法调用。借助这些作用域,您可以使用先前涵盖的每种方法,例如,在何处,在何处加入和包括。所有作用域方法都将返回一个ActiveRecord :: Relation对象,该对象将允许在其上调用其他方法(例如其他作用域)。
为了定义一个简单的作用域,我们在类内部使用了scope方法,并在该作用域被调用时传递我们要运行的查询:
class Article < ActiveRecord::Base
scope :published, -> { where(published: true) }
end
Run Code Online (Sandbox Code Playgroud)
这与定义类方法完全相同,您可以根据个人喜好使用:
class Article < ActiveRecord::Base
def self.published
where(published: true)
end
end
Run Code Online (Sandbox Code Playgroud)
请点击以下链接以获取示例的完整说明。我希望这能帮到您。
http://guides.rubyonrails.org/active_record_querying.html
| 归档时间: |
|
| 查看次数: |
45273 次 |
| 最近记录: |