Skip to content

Commit 74d24ea

Browse files
committed
Merge pull request rails#9497 from route/subclass_from_attrs
Fix ActiveRecord `subclass_from_attrs` when eager_load is false. Conflicts: activerecord/CHANGELOG.md
2 parents dd1d309 + b04051d commit 74d24ea

File tree

4 files changed

+22
-2
lines changed

4 files changed

+22
-2
lines changed

activerecord/CHANGELOG.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
## Rails 4.0.0 (unreleased) ##
22

3+
* Fix ActiveRecord `subclass_from_attrs` when eager_load is false.
4+
It cannot find subclass because all classes are loaded automatically
5+
when it needs.
6+
7+
*Dmitry Vorotilin*
8+
39
* When `:name` option is provided to `remove_index`, use it if there is no
410
index by the conventional name.
511

activerecord/lib/active_record/inheritance.rb

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -170,8 +170,9 @@ def type_condition(table = arel_table)
170170
# this will ignore the inheritance column and return nil
171171
def subclass_from_attrs(attrs)
172172
subclass_name = attrs.with_indifferent_access[inheritance_column]
173-
return nil if subclass_name.blank? || subclass_name == self.name
174-
unless subclass = subclasses.detect { |sub| sub.name == subclass_name }
173+
return if subclass_name.blank? || subclass_name == self.name
174+
subclass = subclass_name.safe_constantize
175+
unless subclasses.include?(subclass)
175176
raise ActiveRecord::SubclassNotFound.new("Invalid single-table inheritance type: #{subclass_name} is not a subclass of #{name}")
176177
end
177178
subclass

activerecord/test/cases/inheritance_test.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,17 @@ def test_new_with_unrelated_type
179179
assert_raise(ActiveRecord::SubclassNotFound) { Company.new(:type => 'Account') }
180180
end
181181

182+
def test_new_with_autoload_paths
183+
path = File.expand_path('../../models/autoloadable', __FILE__)
184+
ActiveSupport::Dependencies.autoload_paths << path
185+
186+
firm = Company.new(:type => 'ExtraFirm')
187+
assert_equal ExtraFirm, firm.class
188+
ensure
189+
ActiveSupport::Dependencies.autoload_paths.reject! { |p| p == path }
190+
ActiveSupport::Dependencies.clear
191+
end
192+
182193
def test_inheritance_condition
183194
assert_equal 10, Company.count
184195
assert_equal 2, Firm.count
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
class ExtraFirm < Company
2+
end

0 commit comments

Comments
 (0)