class DirtySeed::Association

Represents an Active Record association

Public Instance Methods

associated_models() click to toggle source

Returns or defines associated_models @return [Array<Class>] a class inheriting from ApplicationRecord

# File lib/dirty_seed/association.rb, line 38
def associated_models
  polymorphic? ? polymorphic_associations : regular_associations
end
attribute() click to toggle source

Returns the attribute containing the foreign key @return [Symbol]

# File lib/dirty_seed/association.rb, line 22
def attribute
  :"#{name}_id"
end
optional?() click to toggle source

Is the association optional? @return [Boolean] @example

Given Bar.belongs_to(:barable, optional: true)
And self.model == Bar
Then it returns true
# File lib/dirty_seed/association.rb, line 48
def optional?
  options[:optional].present?
end
polymorphic?() click to toggle source

Is the reflection polymorphic? @return [Boolean] @example

Given Bar.belongs_to(:barable, polymorphic: true)
And self.model == Bar
Then it returns true
# File lib/dirty_seed/association.rb, line 58
def polymorphic?
  options[:polymorphic].present?
end
type_key() click to toggle source

Returns the attribute containing the foreign type (for polymorphic associations) @return [Symbol] @example

Given Bar.belongs_to(:barable, polymorphic: true)
And self.model == Bar
Then it returns barable_type
# File lib/dirty_seed/association.rb, line 32
def type_key
  foreign_type&.to_sym
end
value() click to toggle source

Returns a random instance matching the reflection @return [Object, nil] an instance of a class inheriting from ApplicationRecord

# File lib/dirty_seed/association.rb, line 12
def value
  return if associated_models.empty?

  random_model = associated_models.sample
  random_id = random_model.pluck(:id).sample
  random_model.find_by(id: random_id)
end

Private Instance Methods

polymorphic_associations() click to toggle source

Returns the reflected models for a polymorphic association @return [Array<Class>] a class inheriting from ApplicationRecord @example

Given Bar.belongs_to(:barable, polymorphic: true)
And Foo.has_many(:bars, as: :barable)
And Zed.has_many(:bars, as: :barable)
And #model is Bar
Then it returns [Foo, Zed]
# File lib/dirty_seed/association.rb, line 85
def polymorphic_associations
  DirtySeed::DataModel.instance.active_record_models.select do |active_record_model|
    active_record_model.reflections.values.any? do |arm_reflection|
      arm_reflection.options[:as]&.to_sym == name
    end
  end
rescue NameError
  []
end
regular_associations() click to toggle source

Returns the reflected models for a regular association @return [Array<Class>] a class inheriting from ApplicationRecord @example

Given Bar.belongs_to(:foo)
And Foo.has_many(:bars)
And self.model == Bar
Then it returns [Foo]
# File lib/dirty_seed/association.rb, line 71
def regular_associations
  [klass]
rescue NameError
  []
end