Module: InverseOf::Associations::BelongsToPolymorphicAssociation

Defined in:
lib/inverse_of.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



139
140
141
142
# File 'lib/inverse_of.rb', line 139

def self.included(base)
  base.alias_method_chain :replace, :inverse_of
  base.alias_method_chain :find_target, :inverse_of
end

Instance Method Details

#find_target_with_inverse_ofObject



150
151
152
153
154
# File 'lib/inverse_of.rb', line 150

def find_target_with_inverse_of
  target = find_target_without_inverse_of
  set_inverse_instance(target, @owner)
  target
end

#replace_with_inverse_of(record) ⇒ Object



144
145
146
147
148
# File 'lib/inverse_of.rb', line 144

def replace_with_inverse_of(record)
  replace_without_inverse_of(record)
  set_inverse_instance(record, @owner)
  record
end

#set_inverse_instance(record, instance) ⇒ Object



167
168
169
170
171
172
173
# File 'lib/inverse_of.rb', line 167

def set_inverse_instance(record, instance)
  return if record.nil? || !we_can_set_the_inverse_on_this?(record)
  inverse_relationship = @reflection.polymorphic_inverse_of(record.class)
  unless inverse_relationship.nil?
    record.send(:"set_#{inverse_relationship.name}_target", instance)
  end
end

#we_can_set_the_inverse_on_this?(record) ⇒ Boolean

NOTE - for now, we’re only supporting inverse setting from belongs_to back onto has_one associations.

Returns:

  • (Boolean)


158
159
160
161
162
163
164
165
# File 'lib/inverse_of.rb', line 158

def we_can_set_the_inverse_on_this?(record)
  if @reflection.has_inverse?
    inverse_association = @reflection.polymorphic_inverse_of(record.class)
    inverse_association && inverse_association.macro == :has_one
  else
    false
  end
end