Class: DirtySeed::Association
- Inherits:
-
Object
- Object
- DirtySeed::Association
- Extended by:
- MethodMissingHelper
- Defined in:
- lib/dirty_seed/association.rb
Overview
Represents an Active Record association
Instance Attribute Summary collapse
-
#model ⇒ Object
readonly
Returns the value of attribute model.
-
#reflection ⇒ Object
readonly
Returns the value of attribute reflection.
Instance Method Summary collapse
-
#associated_models ⇒ Array<Class>
Returns or defines associated_models.
-
#attribute ⇒ Symbol
Returns the attribute containing the foreign key.
-
#initialize(model, reflection) ⇒ DirtySeed::Association
constructor
Initializes an instance.
-
#name ⇒ String
Returns the reflection name.
-
#polymorphic? ⇒ Boolean
Returns true if the reflection is polymorphic.
-
#type_key ⇒ Symbol
Returns the attribute containing the foreign type (for polymorphic associations).
-
#value ⇒ Object
Returns a random instance matching the reflection.
Methods included from MethodMissingHelper
define_addressee, define_method_missing, define_respond_to_missing?, forward_missing_methods_to
Constructor Details
#initialize(model, reflection) ⇒ DirtySeed::Association
Initializes an instance
15 16 17 18 |
# File 'lib/dirty_seed/association.rb', line 15 def initialize(model, reflection) @model = model @reflection = reflection end |
Instance Attribute Details
#model ⇒ Object (readonly)
Returns the value of attribute model.
9 10 11 |
# File 'lib/dirty_seed/association.rb', line 9 def model @model end |
#reflection ⇒ Object (readonly)
Returns the value of attribute reflection.
9 10 11 |
# File 'lib/dirty_seed/association.rb', line 9 def reflection @reflection end |
Instance Method Details
#associated_models ⇒ Array<Class>
Returns or defines associated_models
52 53 54 |
# File 'lib/dirty_seed/association.rb', line 52 def associated_models polymorphic? ? polymorphic_associations : regular_associations end |
#attribute ⇒ Symbol
Returns the attribute containing the foreign key
36 37 38 |
# File 'lib/dirty_seed/association.rb', line 36 def attribute :"#{name}_id" end |
#name ⇒ String
Returns the reflection name
30 31 32 |
# File 'lib/dirty_seed/association.rb', line 30 def name reflection.name end |
#polymorphic? ⇒ Boolean
Returns true if the reflection is polymorphic
62 63 64 |
# File 'lib/dirty_seed/association.rb', line 62 def polymorphic? reflection.[:polymorphic] end |
#type_key ⇒ Symbol
Returns the attribute containing the foreign type (for polymorphic associations)
46 47 48 |
# File 'lib/dirty_seed/association.rb', line 46 def type_key reflection.foreign_type&.to_sym end |
#value ⇒ Object
Returns a random instance matching the reflection
22 23 24 25 26 |
# File 'lib/dirty_seed/association.rb', line 22 def value random_model = associated_models.sample random_id = random_model.pluck(:id).sample random_model.find_by(id: random_id) end |