ruby rails and sightseeing

Another excellent Edublogs.org weblog

has_finder bzw. jetzt named_scope

Mai 11, 2009 · 1 Comment · Ruby

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

[Edge Rails] More on named_scope

Plugins I’ve Known and Loved #2: has_finder

Tags: ···

One Comment so far ↓

Leave a Comment

*
To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-Spam Image