- 浏览: 163909 次
- 性别:
- 来自: 杭州
文章分类
最新评论
-
GunChin:
有些复杂,看得不是很懂
RAILS -
shellfish:
恩,红帽默认的SELinux的级别是强制,这个一般我不大用,装 ...
华思服务器一个奇怪问题的解决方法 -
机器人:
你说得太好了了了了了了了 子 啊啊啊啊,呼啦啦。
GIT handbook -
hbxiao135:
能介绍下 fat free crm的 流程分析吗?
(CRM)customer relationship management sysetm
今天看了一点关于with_scope的知识,有点感觉,写点东西
with_scope 与 named_scope 没有关系,named_scope 是依赖于with_scope工作的。
1、with_scope
with_scope是给一个model添加一个scope来扩展功能
def self.all_male with_scope(:find => {:conditions => "gender = 'm'"}) do all_active end end def self.all_active with_scope(:find => {:conditions => "status = 'active'"}) do find(:first) end end # User.all_active # SELECT * FROM "users" WHERE (status = 'active') LIMIT 1 # User.all_male # SELECT * FROM "users" WHERE ((gender = 'm') AND (status = 'active')) LIMIT 1
named_scope就是运用with_scope的这种特性来将多个name_scope形成一个query
2、学习编写自己的named_scope
module ActiveRecord module MynamedScope def self.included(base) base.extend ClassMethods end module ClassMethods def mynamed_scope(name,options = {}) puts "name is #{name}" end end end end ActiveRecord::Base.send(:include, ActiveRecord::MynamedScope) class User < ActiveRecord::Base mynamed_scope :active, :conditions => {:status => 'active'} mynamed_scope :male, :conditions => {:gender => 'm'} end
我们就可以通过
User.active User.male User.active.male User.male.active
得到正确的返回结果。
最后结果
module ActiveRecord module MynamedScope def self.included(base) base.extend ClassMethods end module ClassMethods def myscopes read_inheritable_attribute(:myscopes) || write_inheritable_attribute(:myscopes, {}) end def mynamed_scope(name,options = {}) name = name.to_sym myscopes[name] = lambda { |proxy_scope| Scope.new(proxy_scope,options) } (class << self; self end).instance_eval do define_method name do myscopes[name].call(self) end end end class Scope attr_reader :proxy_scope, :proxy_options delegate :with_scope, :to => :proxy_scope def initialize(proxy_scope, options) @proxy_scope, @proxy_options = proxy_scope, options end def inspect load_found end def load_found find(:all) end def method_missing(method, *args, &block) if proxy_scope.myscopes.include?(method) proxy_scope.myscopes[method].call(self) else with_scope :find => proxy_options do proxy_scope.send(method,*args) end end end end # end of class Scope end # end of module ClassMethods end # endof module MynamedScope end ActiveRecord::Base.send(:include, ActiveRecord::MynamedScope) class User < ActiveRecord::Base mynamed_scope :active, :conditions => {:status => 'active'} mynamed_scope :male, :conditions => {:gender => 'm'} end
原文章参考地址:http://www.neeraj.name/blog/articles/751-under-the-hood-how-named_scope-works
文章二、
It looks like Nick Kallen’s wildly popular has_finder
plugin will be making its way
into Rails 2.x in the form of named_scope
. Observe:
All the goodness you’ve come to love in has_finder
is now available as named_scope
– plus you get some extra goodies too. User.all
is given to you for free as an alias for User.find(:all)
.
class User < ActiveRecord::Base named_scope :active, :conditions => {:active => true} named_scope :inactive, :conditions => {:active => false} named_scope :recent, lambda { { :conditions => ['created_at > ?', 1.week.ago] } } end # Standard usage User.active # same as User.find(:all, :conditions => {:active => true}) User.inactive # same as User.find(:all, :conditions => {:active => false}) User.recent # same as User.find(:all, :conditions => ['created_at > ?', 1.week.ago]) # They're nest-able too! User.active.recent # same as: # User.with_scope(:conditions => {:active => true}) do # User.find(:all, :conditions => ['created_at > ?', 1.week.ago]) # end
Advanced
For those with more discriminating needs, don’t forget some of these has_finder
tidbits:
Passing Arguments
Pass in arguments to your named scopes to specify conditions (or other props) at run-time.
class User < ActiveRecord::Base named_scope :registered, lambda { |time_ago| { :conditions => ['created_at > ?', time_ago] } end User.registered 7.days.ago # same as User.find(:all, :conditions => ['created_at > ?', 7.days.ago])
Named Scope Extensions
Extend named scopes (in a similar fashion to association extensions ).
class User < ActiveRecord::Base named_scope :inactive, :conditions => {:active => false} do def activate each { |i| i.update_attribute(:active, true) } end end end # Re-activate all inactive users User.inactive.activate
Anonymous Scopes
You can also pass around scopes as first class objects using scoped
(a named scoped provided to you for free) as a way to build hairy queries on the fly.
# Store named scopes active = User.scoped(:conditions => {:active => true}) recent = User.scoped(:conditions => ['created_at > ?', 7.days.ago]) # Which can be combined recent_active = recent.active # And operated upon recent_active.each { |u| ... }
named_scope
is a truly great
feature. If you haven’t started using it yet, do so. You won’t know how
you lived without it. Major thanks goes out to Nick.
发表评论
-
actionmailer发送邮件失败的问题解决记录
2011-05-24 14:12 2334我们公司的WLAN网管采用ruby on rails架构,同时 ... -
ROR rake
2009-10-20 14:05 1046原文: Ruby on Rails Rake Tuto ... -
控制器内部对请求的操作
2009-10-20 13:41 1843控制器内部对请求的操作 一Action方法 1 ... -
在rails环境中直接执行sql语句而不需要创建MODEL
2009-09-23 10:54 2987标准格式是:ActiveRecord::Base.connec ... -
6 Steps To Refactoring Rails (for Mere Mortals)
2009-07-31 11:26 866Since December, Rails ... -
rails 中简单的创建保存一条信息
2009-07-20 09:43 716Securitylog.new( # :ses ... -
uninstall all gems
2009-07-14 11:31 875GEMS=`gem list --no-versions` ... -
rails 拖拉排序效果demo
2009-06-30 10:55 1353要為Ruby on Rails程式加入拖曳排 ... -
Add jQuery datagrids to your Rails applications
2009-06-03 10:39 1521Add jQuery datagrids to your Ra ... -
Multiple Attachments in Rails
2009-06-03 10:19 1821Multiple Attachments in Rails ... -
REST on Rails之自定义路由
2009-06-03 10:03 1685REST on Rails之自定义路由 from L ... -
自定义will_paginage输出
2009-06-03 09:55 786自定义will_paginage输出 from Le ... -
Rails Cookie测试
2009-06-03 09:48 1077Rails Cookie测试 from Le ... -
配置ActionMailer使用GMail发送邮件
2009-06-03 09:45 1451配置ActionMailer使用GMail发送邮件 ... -
rails 记住跳转前的url
2009-06-02 13:44 1381def store_location ses ... -
给Non-ActiveRecord Objects进行validate
2009-06-02 09:33 886对于非ActiveRecord对象的Validation,我们 ... -
file_column简单的照片上传
2009-04-21 18:19 9661.file_column git clone git:/ ... -
cookie + js动态修改iframe 父窗口的链接参数
2009-04-21 18:12 2870取得 由于最近自己做的项目中采用了目前较为流行的经典左右结构 ... -
git 冲突解决
2009-04-21 17:57 5169比较笨的办法就是直接改本地的代码 先git pull ,他 ... -
git 下gw来查看团队的修改
2009-04-07 15:46 856首先开启一个命令行,在命令行中输入 alias gw= ...
相关推荐
It seems that with each new book the scope gets fuzzier and less precise. When I started writing Test-Driven Java Development the scope of the whole book was done in advance. I had a team working with...
Another type of table lock is a schema stability lock (Sch-S) and is compatible with all table locks except the schema modification lock (Sch-M). The schema modification lock (Sch-M) is incompatible ...
With the JavaMail API, in order to communicate with a server, you need a provider for a protocol. The creation of protocol-specific providers is not covered in this course because Sun provides a ...
Maintaining a uniform style and following conventions means that we can more easily use "pattern-matching" to infer what various symbols are and what invariants are true about them. Creating common, ...
that if something didn't make sense then it didn't deserve a default binding, the user can define these themselves. We also reviewed other editors complete default keybinding sets to find ...
Whether you're a seasoned professional looking to stay updated with the latest trends or a beginner eager to learn the fundamentals, this collection of articles is sure to provide something of ...
3. **Variable Declaration with `var`**: Highlights issues with variable hoisting and scope, especially when using `var`. 4. **Lazy Scoping and Mutability**: Explores the implications of lazy scoping ...
- **例句**: She was angry with him about his irresponsible behavior. #### 24. anxious about/for - **含义**: 对某事感到担忧或焦虑。 - **例句**: I’m very anxious about the outcome of the job interview...
with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute ...
***ernment is trying to do something to boost better understanding between two countries(政府尝试做一些事来增进两国之间的更好理解)。 10. prominent technological success(突出的技术成功)可能是二十...
If you cannot find something you need in the library, contribute. In addition, Struts provides a starting point if you are learning JSP tag technology. • Open source You have all the advantages of...
- About SSL - Support - Release notes - Midware - Known problems - Special thanks Legal issues: ------------- Copyright (C) 1997-2016 by Fran鏾is PIETTE Rue de Grady 24, 4053 Embourg, Belgium ...
Doing Something Cool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 Introducing Our Demo Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ...
NoTE 1 Risk analysis provides the basis for risk evaluation and decisions about risk treatment NoTE 2 Risk analysis includes risk estimation 3.11 risk assessment overall process of risk ...
About Python ............................................................................................1 What Is Python? ................................................................................