Class: DirtySeed::Association
- Inherits:
-
SimpleDelegator
- Object
- SimpleDelegator
- DirtySeed::Association
- Defined in:
- lib/dirty_seed/association.rb
Overview
Represents an Active Record association
Instance Method Summary collapse
-
#associated_models ⇒ Array<Class>
Returns or defines associated_models.
-
#attribute ⇒ Symbol
Returns the attribute containing the foreign key.
- #initialize(reflection) ⇒ DirtySeed::Association constructor
-
#optional? ⇒ Boolean
Is the association optional?.
-
#polymorphic? ⇒ Boolean
Is the reflection polymorphic?.
-
#type_key ⇒ Symbol
Returns the attribute containing the foreign type (for polymorphic associations).
-
#value ⇒ Object?
Returns a random instance matching the reflection.
Constructor Details
Instance Method Details
#associated_models ⇒ Array<Class>
Returns or defines associated_models
38 39 40 |
# File 'lib/dirty_seed/association.rb', line 38 def associated_models polymorphic? ? polymorphic_associations : regular_associations end |
#attribute ⇒ Symbol
Returns the attribute containing the foreign key
22 23 24 |
# File 'lib/dirty_seed/association.rb', line 22 def attribute :"#{name}_id" end |
#optional? ⇒ Boolean
Is the association optional?
48 49 50 |
# File 'lib/dirty_seed/association.rb', line 48 def optional? [:optional].present? end |
#polymorphic? ⇒ Boolean
Is the reflection polymorphic?
58 59 60 |
# File 'lib/dirty_seed/association.rb', line 58 def polymorphic? [:polymorphic].present? end |
#type_key ⇒ Symbol
Returns the attribute containing the foreign type (for polymorphic associations)
32 33 34 |
# File 'lib/dirty_seed/association.rb', line 32 def type_key foreign_type&.to_sym end |
#value ⇒ Object?
Returns a random instance matching the reflection
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 |