Permalink
Browse files

Use the correct class when loading instances for descendents of model…

… classes that use single table inheritance

Before, only the model class that loaded the
single_table_inheritance plugin had the logic to return instances
of subclasses.  This copies that logic into subclasses, so that if
you load all instances of a subclass, it can return instances of
subsubclasses.  Thanks to Max Aller on sequel-talk for pointing
out this bug.
  • Loading branch information...
1 parent 66be40d commit c9db41ce9886e8b9596038fb2ca8998edfd9ade6 @jeremyevans committed Mar 14, 2011
Showing with 15 additions and 0 deletions.
  1. +2 −0 CHANGELOG
  2. +2 −0 lib/sequel/plugins/single_table_inheritance.rb
  3. +11 −0 spec/extensions/single_table_inheritance_spec.rb
View
@@ -1,5 +1,7 @@
=== HEAD
+* Use the correct class when loading instances for descendents of model classes that use single table inheritance (jeremyevans)
+
* Support for COLLATE in column definitions (jfirebaugh)
* Don't use a schema when creating a temporary table (jeremyevans)
@@ -108,8 +108,10 @@ def inherited(subclass)
key = skm[subclass]
sti_subclass_added(key)
ska = [key]
+ rp = dataset.row_proc
subclass.set_dataset(sd.filter(SQL::QualifiedIdentifier.new(table_name, sk)=>ska), :inherited=>true)
subclass.instance_eval do
+ dataset.row_proc = rp
@sti_key = sk
@sti_key_array = ska
@sti_dataset = sd
@@ -54,6 +54,17 @@ def @ds.fetch_rows(sql)
StiTest.all.collect{|x| x.class}.should == [StiTest, StiTestSub1, StiTestSub2]
end
+ it "should return rows with the correct class for subclasses based on the polymorphic_key value" do
+ class ::StiTestSub1Sub < StiTestSub1
+ end
+ ds = StiTestSub1.dataset
+ def ds.fetch_rows(sql)
+ yield({:kind=>'StiTestSub1'})
+ yield({:kind=>'StiTestSub1Sub'})
+ end
+ StiTestSub1.all.collect{|x| x.class}.should == [StiTestSub1, StiTestSub1Sub]
+ end
+
it "should fallback to the main class if the given class does not exist" do
def @ds.fetch_rows(sql)
yield({:kind=>'StiTestSub3'})

0 comments on commit c9db41c

Please sign in to comment.