aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/test
diff options
context:
space:
mode:
authorGeorge Claghorn <george.claghorn@gmail.com>2017-03-17 10:29:19 -0400
committerDavid Heinemeier Hansson <david@loudthinking.com>2017-03-17 15:29:19 +0100
commit73b86ac58b61b4c7b888962252a1a86dffb24081 (patch)
treeea34e055f17867f3811a874bdc51461b40fc417f /activerecord/test
parenteadbc82c47fd157ed4f1eb4c4983ab0734023106 (diff)
downloadrails-73b86ac58b61b4c7b888962252a1a86dffb24081.tar.gz
rails-73b86ac58b61b4c7b888962252a1a86dffb24081.tar.bz2
rails-73b86ac58b61b4c7b888962252a1a86dffb24081.zip
Add :default option to belongs_to (#28453)
Use it to specify that an association should be initialized with a particular record before validation. For example: # Before belongs_to :account before_validation -> { self.account ||= Current.account } # After belongs_to :account, default: -> { Current.account }
Diffstat (limited to 'activerecord/test')
-rw-r--r--activerecord/test/cases/associations/belongs_to_associations_test.rb20
1 files changed, 20 insertions, 0 deletions
diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb
index 5875a1871f..5b08ba1358 100644
--- a/activerecord/test/cases/associations/belongs_to_associations_test.rb
+++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb
@@ -116,6 +116,26 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
ActiveRecord::Base.belongs_to_required_by_default = original_value
end
+ def test_default
+ david = developers(:david)
+ jamis = developers(:jamis)
+
+ model = Class.new(ActiveRecord::Base) do
+ self.table_name = "ships"
+ def self.name; "Temp"; end
+ belongs_to :developer, default: -> { david }
+ end
+
+ ship = model.create!
+ assert_equal david, ship.developer
+
+ ship = model.create!(developer: jamis)
+ assert_equal jamis, ship.developer
+
+ ship.update!(developer: nil)
+ assert_equal david, ship.developer
+ end
+
def test_default_scope_on_relations_is_not_cached
counter = 0