Report abuse

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
require 'rubygems'
require 'active_record'

ActiveRecord::Base.establish_connection(
  :adapter => 'sqlite3', 
  :dbfile  => ':memory:')

# ActiveRecord::Base.logger = Logger.new(STDOUT)

ActiveRecord::Schema.define do 
  create_table 'scores' do |t|
    t.column 'name',    :string
    t.column 'grade',   :string
    t.column 'type',    :string
  end
end

class Score < ActiveRecord::Base
end

class District < Score
end

class Borough < Score
end

# can't assign using Score.create(..., :type => "District")
District.create(:name => "Bob", :grade => "A")
District.create(:name => "Jim", :grade => "F")
Borough.create(:name => "Mac", :grade => "C")
Borough.create(:name => "Bud", :grade => "D")

puts "-------STI-------"
puts "Districts: #{District.find(:all).map(&:name).join(',')} (#{District.count})"
puts "Bouroughs: #{Borough.find(:all).map(&:name).join(',')} (#{Borough.count})"
puts "-------STI-------\n\n"

########################################
### Reimplemented using named_scopes ###
########################################

class Score < ActiveRecord::Base
  named_scope :districts, :conditions => {:type => 'District'}
  named_scope :boroughs, :conditions => {:type => 'Borough'}
end

class District < Score
end

class Borough < Score
end

puts "---named_scopes----"
puts "Districts: #{Score.districts.map(&:name).join(',')} (#{Score.districts.count})"
puts "Boroughs: #{Score.boroughs.map(&:name).join(',')} (#{Score.boroughs.count})"
puts "---named_scopes----\n\n"