module Sack::Database::Model::Relationships::ClassMethods
Class Methods: Collection of methods to be injected into anything that includes this module.
Class Methods
Class Methods
Public Instance Methods
belongs_to(options)
click to toggle source
Belongs To: Defines the 'slave' end of any relationship (the one that holds the other entity's ID). @param [Object] options Either a Symbol indicating both the name of the relationship and the target model, or an option Hash defining the relationship - see README
# File lib/sack/database/model/relationships/belongs_to.rb, line 22 def belongs_to options # Check Options if options.is_a? Hash # Internalise Options (so we can mess it up) options = options.clone # Pull Relationship Name & Target Model name, target_model_name = options.first options.delete name else # Acquire everything from just a Symbol name = options target_model_name = name end # Construct Proxy Method Module proxy = Module.new do # Proxy Method for Relationship: # Allows fetching entities for a given belongs-to relationship. define_method name do |db, data| # Find Target Model target_model = @model_root.const_get target_model_name.to_s.camelcase # Fetch Relationship Entity target_model.find db, data[name] end end # Extend Model with Proxy @model.extend proxy end
has_many(options)
click to toggle source
Has Many: Defines the 'one' side a one-to-many relationship. @param [Hash] options Options defining the relationship - see README
# File lib/sack/database/model/relationships/has_many.rb, line 22 def has_many options # Internalise Options (so we can mess it up) options = options.dclone # Pull Relationship Name & Target Model name, target_model_name = options.first options.delete name # Determine Foreign Key (which field in the remote model holds our ID) foreign_key = options[:fk] || table_name # Register Relationship relationships[name] = { target: target_model_name, fk: foreign_key, options: options.dclone } # Construct Proxy Method Module proxy = Module.new do # Proxy Method for Relationship: # Allows fetching entities for a given has-many relationship. define_method name do |db, data| # Find Target Model target_model = @model_root.const_get target_model_name.to_s.camelcase # Fetch Relationship Entities target_model.fetch_by db, foreign_key, data[:id] end end # Extend Model with Proxy @model.extend proxy end
relationships()
click to toggle source
Relationships: Gets the relationships for the Model
.
# File lib/sack/database/model/relationships.rb, line 34 def relationships @relationships ||= {} end