Class: Seedie::Associations::HasOne

Inherits:
BaseAssociation show all
Defined in:
lib/seedie/associations/has_one.rb

Constant Summary

Constants inherited from BaseAssociation

BaseAssociation::DEFAULT_COUNT, BaseAssociation::INDEX

Instance Attribute Summary

Attributes inherited from BaseAssociation

#association_config, #model, #record, #reporters

Instance Method Summary collapse

Methods inherited from BaseAssociation

#generate_association, #initialize

Methods included from Reporters::Reportable

#add_observers, #report

Constructor Details

This class inherits a constructor from Seedie::Associations::BaseAssociation

Instance Method Details

#generate_associationsObject



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/seedie/associations/has_one.rb', line 6

def generate_associations
  return if association_config["has_one"].nil?

  report(:has_one_start)

  association_config["has_one"].each do |association_name, association_config|
    reflection = model.reflect_on_association(association_name)
    association_class = reflection.klass
    count = get_association_count(association_config)

    report(:associated_records, count: count, name: association_name, parent_name: model.to_s)
    raise InvalidAssociationConfigError, "has_one association cannot be more than 1" if count > 1

    config = only_count_given?(association_config) ? {} : association_config
    field_values_set = FieldValuesSet.new(association_class, config, INDEX).generate_field_values
    parent_field_set = generate_associated_field(record.id, reflection.foreign_key)

    record_creator = Model::Creator.new(association_class, reporters)
    record_creator.create!(field_values_set.merge!(parent_field_set))
  end
end