Handle non-default inheritance column.
This commit is contained in:
parent
0cf5b2932c
commit
20e529576b
|
@ -52,7 +52,8 @@ class Version < ActiveRecord::Base
|
|||
if item
|
||||
model = item
|
||||
else
|
||||
class_name = attrs['type'].blank? ? item_type : attrs['type']
|
||||
inheritance_column_name = item_type.constantize.inheritance_column
|
||||
class_name = attrs[inheritance_column_name].blank? ? item_type : attrs[inheritance_column_name]
|
||||
klass = class_name.constantize
|
||||
model = klass.new
|
||||
end
|
||||
|
|
|
@ -0,0 +1,3 @@
|
|||
class Animal < ActiveRecord::Base
|
||||
has_paper_trail
|
||||
end
|
|
@ -0,0 +1,3 @@
|
|||
class Cat < Animal
|
||||
set_inheritance_column 'species'
|
||||
end
|
|
@ -0,0 +1,3 @@
|
|||
class Dog < Animal
|
||||
set_inheritance_column 'species'
|
||||
end
|
|
@ -82,14 +82,20 @@ class SetUpTestTables < ActiveRecord::Migration
|
|||
create_table :songs, :force => true do |t|
|
||||
t.integer :length
|
||||
end
|
||||
|
||||
|
||||
create_table :posts, :force => true do |t|
|
||||
t.string :title
|
||||
t.string :content
|
||||
end
|
||||
|
||||
create_table :animals, :force => true do |t|
|
||||
t.string :name
|
||||
t.string :species # single table inheritance column
|
||||
end
|
||||
end
|
||||
|
||||
def self.down
|
||||
drop_table :animals
|
||||
drop_table :posts
|
||||
drop_table :songs
|
||||
drop_table :people
|
||||
|
|
Binary file not shown.
|
@ -0,0 +1,32 @@
|
|||
require 'test_helper'
|
||||
|
||||
class InheritanceColumnTest < ActiveSupport::TestCase
|
||||
|
||||
context 'STI models' do
|
||||
setup do
|
||||
@animal = Animal.create :name => 'Animal'
|
||||
@animal.update_attributes :name => 'Animal from the Muppets'
|
||||
@animal.update_attributes :name => 'Animal Muppet'
|
||||
|
||||
@dog = Dog.create :name => 'Snoopy'
|
||||
@dog.update_attributes :name => 'Scooby'
|
||||
@dog.update_attributes :name => 'Scooby Doo'
|
||||
|
||||
@cat = Cat.create :name => 'Garfield'
|
||||
@cat.update_attributes :name => 'Garfield (I hate Mondays)'
|
||||
@cat.update_attributes :name => 'Garfield The Cat'
|
||||
end
|
||||
|
||||
should 'work with custom STI inheritance column' do
|
||||
assert_equal 9, Version.count
|
||||
assert_equal 3, @animal.versions.count
|
||||
assert_equal 3, @dog.versions.count
|
||||
assert_equal 3, @cat.versions.count
|
||||
|
||||
assert_equal 'Animal from the Muppets', @animal.versions.last.reify.name
|
||||
assert_equal 'Scooby', @dog.versions.last.reify.name
|
||||
assert_equal 'Garfield (I hate Mondays)', @cat.versions.last.reify.name
|
||||
end
|
||||
end
|
||||
|
||||
end
|
Loading…
Reference in New Issue