diff options
Diffstat (limited to 'activerecord')
-rw-r--r-- | activerecord/lib/active_record/associations/belongs_to_association.rb | 2 | ||||
-rw-r--r-- | activerecord/test/cases/associations/belongs_to_associations_test.rb | 18 |
2 files changed, 19 insertions, 1 deletions
diff --git a/activerecord/lib/active_record/associations/belongs_to_association.rb b/activerecord/lib/active_record/associations/belongs_to_association.rb index a2432e389a..0e61dbfb00 100644 --- a/activerecord/lib/active_record/associations/belongs_to_association.rb +++ b/activerecord/lib/active_record/associations/belongs_to_association.rb @@ -22,7 +22,7 @@ module ActiveRecord end def default(&block) - writer(instance_exec(&block)) if reader.nil? + writer(owner.instance_exec(&block)) if reader.nil? end def reset diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb index 5b08ba1358..c8b26232b6 100644 --- a/activerecord/test/cases/associations/belongs_to_associations_test.rb +++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb @@ -136,6 +136,24 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase assert_equal david, ship.developer end + def test_default_with_lambda + model = Class.new(ActiveRecord::Base) do + self.table_name = "ships" + def self.name; "Temp"; end + belongs_to :developer, default: -> { default_developer } + + def default_developer + Developer.first + end + end + + ship = model.create! + assert_equal developers(:david), ship.developer + + ship = model.create!(developer: developers(:jamis)) + assert_equal developers(:jamis), ship.developer + end + def test_default_scope_on_relations_is_not_cached counter = 0 |