diff options
author | George Claghorn <george@basecamp.com> | 2017-04-27 12:35:48 -0400 |
---|---|---|
committer | George Claghorn <george@basecamp.com> | 2017-04-27 12:36:50 -0400 |
commit | 4f8f5f59fc37a6adb71979eec66488f4ad08bffa (patch) | |
tree | 60f562ed30068f0ff2dd6dedd9b9bb2df8e8b287 | |
parent | 5974334aeb23c21100af5bf877b385dbbe762bc6 (diff) | |
download | rails-4f8f5f59fc37a6adb71979eec66488f4ad08bffa.tar.gz rails-4f8f5f59fc37a6adb71979eec66488f4ad08bffa.tar.bz2 rails-4f8f5f59fc37a6adb71979eec66488f4ad08bffa.zip |
Evaluate belongs_to :default option against the owner, not the association
-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 |