Class: DynamicActiveModel::ForeignKey
- Inherits:
-
Object
- Object
- DynamicActiveModel::ForeignKey
- Defined in:
- lib/dynamic-active-model/foreign_key.rb
Overview
The ForeignKey class manages foreign key relationships for a model. It provides functionality for:
-
Tracking foreign key columns
-
Generating standard foreign key names
-
Managing custom relationship names
-
Configuring the foreign key suffix
Constant Summary collapse
- DEFAULT_ID_SUFFIX =
Default suffix used for foreign key columns
'_id'
Instance Attribute Summary collapse
-
#keys ⇒ Hash
readonly
Mapping of foreign key columns to relationship names.
-
#model ⇒ Class
readonly
The model this foreign key belongs to.
Class Method Summary collapse
-
.id_suffix ⇒ String
Gets the current foreign key suffix.
-
.id_suffix=(val) ⇒ Object
Sets a custom foreign key suffix.
Instance Method Summary collapse
-
#add(key, relationship_name = nil) ⇒ Object
Adds a foreign key to track.
-
#generate_foreign_key(table_name) ⇒ String
Generates a standard foreign key name from a table name.
-
#initialize(model) ⇒ ForeignKey
constructor
Initializes a new ForeignKey instance.
Constructor Details
#initialize(model) ⇒ ForeignKey
Initializes a new ForeignKey instance
42 43 44 45 46 |
# File 'lib/dynamic-active-model/foreign_key.rb', line 42 def initialize(model) @model = model @keys = {} add(generate_foreign_key(model.table_name)) end |
Instance Attribute Details
#keys ⇒ Hash (readonly)
Returns Mapping of foreign key columns to relationship names.
23 24 25 |
# File 'lib/dynamic-active-model/foreign_key.rb', line 23 def keys @keys end |
#model ⇒ Class (readonly)
Returns The model this foreign key belongs to.
20 21 22 |
# File 'lib/dynamic-active-model/foreign_key.rb', line 20 def model @model end |
Class Method Details
.id_suffix ⇒ String
Gets the current foreign key suffix
30 31 32 |
# File 'lib/dynamic-active-model/foreign_key.rb', line 30 def self.id_suffix @id_suffix || DEFAULT_ID_SUFFIX end |
.id_suffix=(val) ⇒ Object
Sets a custom foreign key suffix
36 37 38 |
# File 'lib/dynamic-active-model/foreign_key.rb', line 36 def self.id_suffix=(val) @id_suffix = val end |
Instance Method Details
#add(key, relationship_name = nil) ⇒ Object
Adds a foreign key to track
51 52 53 |
# File 'lib/dynamic-active-model/foreign_key.rb', line 51 def add(key, relationship_name = nil) @keys[key] = relationship_name || model.table_name.underscore end |
#generate_foreign_key(table_name) ⇒ String
Generates a standard foreign key name from a table name
58 59 60 |
# File 'lib/dynamic-active-model/foreign_key.rb', line 58 def generate_foreign_key(table_name) table_name.underscore.singularize + self.class.id_suffix end |