module Mongoid::Association::Referenced::HasOne::Buildable
The Builder behavior for has_one associations.
@since 7.0
Public Instance Methods
build(base, object, type = nil)
click to toggle source
This method either takes an _id or an object and queries for the inverse side using the id or sets the object after clearing the associated object.
@return [ Document ] A single document.
# File lib/mongoid/association/referenced/has_one/buildable.rb, line 16 def build(base, object, type = nil) if query?(object) if !base.new_record? execute_query(object, base) end else clear_associated(object) object end end
Private Instance Methods
clear_associated(object)
click to toggle source
# File lib/mongoid/association/referenced/has_one/buildable.rb, line 29 def clear_associated(object) if object && (associated = object.send(inverse)) associated.substitute(nil) end end
execute_query(object, base)
click to toggle source
# File lib/mongoid/association/referenced/has_one/buildable.rb, line 40 def execute_query(object, base) query_criteria(object, base).limit(-1).first(id_sort: :none) end
query?(object)
click to toggle source
# File lib/mongoid/association/referenced/has_one/buildable.rb, line 52 def query?(object) object && !object.is_a?(Mongoid::Document) end
query_criteria(object, base)
click to toggle source
# File lib/mongoid/association/referenced/has_one/buildable.rb, line 35 def query_criteria(object, base) crit = klass.where(foreign_key => object) with_polymorphic_criterion(crit, base) end
with_polymorphic_criterion(criteria, base)
click to toggle source
# File lib/mongoid/association/referenced/has_one/buildable.rb, line 44 def with_polymorphic_criterion(criteria, base) if polymorphic? criteria.where(type => base.class.name) else criteria end end