diff --git a/lib/mongoid/association/nested/one.rb b/lib/mongoid/association/nested/one.rb index 5fbc9397da..637ddb00cf 100644 --- a/lib/mongoid/association/nested/one.rb +++ b/lib/mongoid/association/nested/one.rb @@ -53,12 +53,25 @@ def initialize(association, attributes, options) @attributes = attributes.with_indifferent_access @association = association @options = options - @class_name = options[:class_name] ? options[:class_name].constantize : association.klass + @class_name = class_from(options[:class_name]) @destroy = @attributes.delete(:_destroy) end private + # Coerces the argument into a class, or defaults to the association's class. + # + # @param [ String | Mongoid::Document | nil ] name_or_class the value to coerce + # + # @return [ Mongoid::Document ] the resulting class + def class_from(name_or_class) + case name_or_class + when nil, false then association.klass + when String then name_or_class.constantize + else name_or_class + end + end + # Extracts and converts the id to the expected type. # # @return [ BSON::ObjectId | String | Object | nil ] The converted id, diff --git a/spec/mongoid/attributes/nested_spec.rb b/spec/mongoid/attributes/nested_spec.rb index 8943d382e3..39447a7892 100644 --- a/spec/mongoid/attributes/nested_spec.rb +++ b/spec/mongoid/attributes/nested_spec.rb @@ -2,6 +2,7 @@ # rubocop:todo all require "spec_helper" +require 'support/models/sandwich' require_relative '../association/referenced/has_many_models' require_relative '../association/referenced/has_and_belongs_to_many_models' require_relative './nested_spec_models'