Rails 中命名范围的意义是什么? [英] What's the significance of named scope in Rails?

查看:61
本文介绍了Rails 中命名范围的意义是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在了解详情之前.

问题 1:-- 这里的范围是什么意思(即命名为**范围)?**

Question 1:-- What's the meaning of scope here (ie named **scope)?**

使用命名范围有什么好处?

现在:-

来自 Agile Development with Rails 一书:--

class Order < ActiveRecord::Base
   named_scope :last_n_days, lambda { |days| {:conditions =>
  ['updated < ?' , days] } }

 named_scope :checks, :conditions => {:pay_type => :check}
end

这样的命名范围将使查找上周的订单价值成为快照.

Such a named scope would make finding the last week's worth of orders a snap.

   orders = Orders.last_n_days(7)

范围也可以组合

orders = Orders.checks.last_n_days(7)

为什么我们在这里使用 named_scope.我们可以使用方法来做同样的事情.我们使用 named_scope 有什么特别之处.

推荐答案

Scope 仅表示某个选定的范围.所以如果你使用:

Scope simply means some selected range. So if you use:

orders = Orders.checks.last_n_days(7)

那么您只想从订单中选择过去 7 天内使用支票付款的订单.所以你范围"订单.

then you want to select from orders only that orders that are payed with check and are within last 7 days. So you 'scope' orders.

为什么不使用方法?

命名范围是方法.这只是定义它们的一种更简单的方法,因此您不必关心所有细节,您可以愉快地使用它!

Named scopes are methods. It is just a simpler way of definig them so you don't have to care about all details and you can be happy using it!

请记住,作用域只是向 sql 查询添加一些条件(和其他内容).

And remember that scopes are just adding some conditions (and other stuff) to sql query.

这篇关于Rails 中命名范围的意义是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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