something about with_scope
7161 단어 작업BlogRailsActiveRecord
with_scope와namedscope 괜찮아,namedscope는 with에 의존하는scope에서 일해요.
1、with_scope
with_scope는 모델에 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는 위드를 활용하는...scope의 이러한 특성으로 여러 namescope는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
기사 2.
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.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
개인 FLEX 지식 라이브러리 작업 노트[size=large]1、 이 방법은 TileWindows 팝업 창에 있습니다. TitleWindows의 maxWidth와 maxHeight를 지정하지 않으면 최대 값이 화면 전체에 깔립니다. 페이지의minHeigh...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.