Rails 中命名范围的意义是什么?
在了解详细信息之前。
问题 1:-- 此处范围的含义是什么(即命名 **范围)?**
使用命名范围有什么好处?
现在:-
来自《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
这样的命名范围将使查找上周的订单价值成为可能 折断。
orders = Orders.last_n_days(7)
范围也可以组合
orders = Orders.checks.last_n_days(7)
为什么我们在这里使用named_scope。我们可以使用方法做同样的事情。我们使用named_scope得到了什么特别的东西。
Before going for details.
Question 1:-- What's the meaning of scope here (ie named **scope)?**
what's the benefits of using named scope?
Now:-
from Agile Development with Rails book:--
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)
Scopes can also be combined
orders = Orders.checks.last_n_days(7)
why we are using named_scope here. We can do the same using methods. What's special thing we got using named_scope.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我们得到更短、可链接、更易读的代码:
比 Rails3 更具可读性、更短且不可链接,
优势会更大,因为 arel。有关更多信息,我建议观看 Railscast:
we get shorter, chainable, and more readable code:
is much more readable, shorter and not chainable than
In Rails3 the advantage will be even greater, because of arel. For more information I recommend watching the Railscasts:
范围只是指一些选定的范围。因此,如果您使用:
那么您只想从订单中选择最近 7 天内通过支票付款的订单。所以你可以“范围”定单。
命名范围是方法。这只是一种更简单的定义它们的方法,因此您不必关心所有细节,并且可以愉快地使用它!
请记住,范围只是向 sql 查询添加一些条件(和其他内容)。
Scope simply means some selected range. So if you use:
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!
And remember that scopes are just adding some conditions (and other stuff) to sql query.
named_scope 对于两种情况非常有用
更好的可读性
有了好的named_scope,您可以更轻松地了解您真正想要搜索的内容。
链接
所有named_scope都可以链接。所以如果你想制作一个搜索系统,这很容易做到。在痛苦之前就做到了。
您可以动态生成链。
The named_scope are really useful for 2 cases
better readabililty
With good named_scope you can understand more easily what you want really search.
Chaining
All named_scope can be chained. So if you want made a search system, it's easy to do. Made it before it was painful.
You can generate chain it on the fly.