Meine Lieblingsplugin has_finder ist ja jetzt fester Bestandteil von ActiveRecord. Neuer Name: named_scope
Beispiel mit der opengeodb:
# == Schema Information
# Schema version: 20090410083430
#
# Table name: geodb_tree
#
# loc_id :integer(4) not null
# lft :integer(4) not null
# rgt :integer(4) not null
# level :integer(1) not null
#
class Tree < ActiveRecord::Base
set_table_name "geodb_tree"
#klassische Variante
def self.bundeslaender
Tree.find(:all,:select=>["g2.loc_id,g2.level, gt.text_val "],:from=>["geodb_textdata AS gt,geodb_tree AS g,geodb_tree AS g2"],:conditions=>["g.loc_id =105 AND g2.lft > g.lft AND g2.rgt < g.rgt AND g2.level = 3 AND gt.loc_id = g2.loc_id AND gt.text_type = 500100000 and valid_until>NOW() and text_locale=?","de"])
end
#jetzt als has_finder
named_scope :bl ,:select=>["g2.loc_id,g2.level, gt.text_val "],:from=>["geodb_textdata AS gt,geodb_tree AS g,geodb_tree AS g2"],:conditions=>["g.loc_id =105 AND g2.lft > g.lft AND g2.rgt < g.rgt AND g2.level = 3 AND gt.loc_id = g2.loc_id AND gt.text_type = 500100000 and valid_until>NOW() and text_locale=?","de"]
end
Okay, ist nix besonderes. Wir können aber auch kombinieren.
Anderes Beispiel:
class City < ActiveRecord::Base
named_scope :public ,:conditions => {:public => true}
named_scope :city, :conditions => {:loc_level => 6}
end
Aufruf:
>> City.public
>> City.public.city
>> City.public.city.find(:first)
Viel Spaß!
Weiter Links zum Thema:
What’s New in Edge Rails: Has Finder Functionality

[...] meinem Zweitblog( die nächste Blogleiche ) habe ich einige has_finder / named_scope Beispiele [...]