2008年7月31日 星期四

named_scope

http://pivots.pivotallabs.com/users/nick/blog/articles/284-hasfinder-it-s-now-easier-than-ever-to-create-complex-re-usable-sql-queries
http://ryandaigle.com/articles/2008/3/24/what-s-new-in-edge-rails-has-finder-functionality

has_finder and scope_out are instead of named_scope
class User < ActiveRecord::Base
named_scope :registered, lambda { |time_ago| { :conditions => ['created_at > ?', time_ago] }
named_scope :has_registered, lambda {|*args| { :conditions => ['created_at > ?', (args.first || 2.weeks.ago)]}}
named_scope :adult, :include => :profile, :conditions => {'profiles.adult' => true}
end
還可以設預設值喔
User.registered 7.days.ago # same as User.find(:all, :conditions => ['created_at > ?', 7.days.ago])


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

# 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| ... }

def find_records(result)
scope = Record.scoped({})
scope = scope.scoped :conditions => ["records.success = ?", result] unless result.blank?
scope
end

沒有留言: