Class: DirtySeed::Association

Inherits:
SimpleDelegator
  • Object
show all
Defined in:
lib/dirty_seed/association.rb

Overview

Represents an Active Record association

Instance Method Summary collapse

Constructor Details

#initialize(reflection) ⇒ DirtySeed::Association

Parameters:

  • reflection (ActiveRecord::Reflection::BelongsToReflection)


# File 'lib/dirty_seed/association.rb', line 6


Instance Method Details

#associated_modelsArray<Class>

Returns or defines associated_models

Returns:

  • (Array<Class>)

    a class inheriting from ApplicationRecord



38
39
40
# File 'lib/dirty_seed/association.rb', line 38

def associated_models
  polymorphic? ? polymorphic_associations : regular_associations
end

#attributeSymbol

Returns the attribute containing the foreign key

Returns:

  • (Symbol)


22
23
24
# File 'lib/dirty_seed/association.rb', line 22

def attribute
  :"#{name}_id"
end

#optional?Boolean

Is the association optional?

Examples:

Given Bar.belongs_to(:barable, optional: true)
And self.model == Bar
Then it returns true

Returns:

  • (Boolean)


48
49
50
# File 'lib/dirty_seed/association.rb', line 48

def optional?
  options[:optional].present?
end

#polymorphic?Boolean

Is the reflection polymorphic?

Examples:

Given Bar.belongs_to(:barable, polymorphic: true)
And self.model == Bar
Then it returns true

Returns:

  • (Boolean)


58
59
60
# File 'lib/dirty_seed/association.rb', line 58

def polymorphic?
  options[:polymorphic].present?
end

#type_keySymbol

Returns the attribute containing the foreign type (for polymorphic associations)

Examples:

Given Bar.belongs_to(:barable, polymorphic: true)
And self.model == Bar
Then it returns barable_type

Returns:

  • (Symbol)


32
33
34
# File 'lib/dirty_seed/association.rb', line 32

def type_key
  foreign_type&.to_sym
end

#valueObject?

Returns a random instance matching the reflection

Returns:

  • (Object, nil)

    an instance of a class inheriting from ApplicationRecord



12
13
14
15
16
17
18
# 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