diff options
3 files changed, 16 insertions, 2 deletions
diff --git a/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb b/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb index a5c9f1666e..b888148841 100644 --- a/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb +++ b/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb @@ -62,13 +62,13 @@ module ActiveRecord::Associations::Builder # :nodoc: end def self.add_left_association(name, options) - belongs_to name, options + belongs_to name, required: false, **options self.left_reflection = _reflect_on_association(name) end def self.add_right_association(name, options) rhs_name = name.to_s.singularize.to_sym - belongs_to rhs_name, options + belongs_to rhs_name, required: false, **options self.right_reflection = _reflect_on_association(rhs_name) end diff --git a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb index e9f679e6de..ccb062f991 100644 --- a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb @@ -976,4 +976,10 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase assert preloaded_first_project.salaried_developers.loaded?, true assert_equal first_project.salaried_developers.size, preloaded_first_project.salaried_developers.size end + + def test_has_and_belongs_to_many_is_useable_with_belongs_to_required_by_default + assert_difference "Project.first.developers_required_by_default.size", 1 do + Project.first.developers_required_by_default.create!(name: "Sean", salary: 50000) + end + end end diff --git a/activerecord/test/models/project.rb b/activerecord/test/models/project.rb index b034e0e267..efa8246f1e 100644 --- a/activerecord/test/models/project.rb +++ b/activerecord/test/models/project.rb @@ -15,6 +15,14 @@ class Project < ActiveRecord::Base belongs_to :firm has_one :lead_developer, through: :firm, inverse_of: :contracted_projects + begin + previous_value, ActiveRecord::Base.belongs_to_required_by_default = + ActiveRecord::Base.belongs_to_required_by_default, true + has_and_belongs_to_many :developers_required_by_default, class_name: "Developer" + ensure + ActiveRecord::Base.belongs_to_required_by_default = previous_value + end + attr_accessor :developers_log after_initialize :set_developers_log |