Module: Associatable
- Included in:
- WORMY::Base
- Defined in:
- lib/wormy/associatable.rb
Instance Method Summary collapse
- #association_options ⇒ Object
- #belongs_to(name, options = {}) ⇒ Object
- #has_many(name, options = {}) ⇒ Object
- #has_many_through(association_name, through:, source:) ⇒ Object
- #has_one_through(association_name, through:, source:) ⇒ Object
Instance Method Details
#association_options ⇒ Object
37 38 39 |
# File 'lib/wormy/associatable.rb', line 37 def @association_options ||= {} end |
#belongs_to(name, options = {}) ⇒ Object
41 42 43 44 45 46 47 48 49 50 |
# File 'lib/wormy/associatable.rb', line 41 def belongs_to(name, = {}) = BelongsToOptions.new(name, ) define_method(name) do key_value = self.send(.foreign_key) .model_class.where(.primary_key => key_value).first end self.[name] = end |
#has_many(name, options = {}) ⇒ Object
52 53 54 55 56 57 58 59 60 |
# File 'lib/wormy/associatable.rb', line 52 def has_many(name, = {}) = HasManyOptions.new(name, self, ) define_method(name) do .model_class.where(.foreign_key => self.id) end self.[name] = end |
#has_many_through(association_name, through:, source:) ⇒ Object
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 |
# File 'lib/wormy/associatable.rb', line 88 def has_many_through(association_name, through:, source:) define_method(association_name) do = self.class.[through] = .model_class.[source] source_table = .table_name through_table = .table_name results = WORMY::DBConnection.execute(<<-SQL, self.id) SELECT #{source_table}.* FROM #{through_table} JOIN #{source_table} ON #{source_table}.#{.foreign_key} = #{through_table}.#{.primary_key} WHERE #{through_table}.#{.foreign_key} = ? SQL .model_class.parse_all(results) end end |
#has_one_through(association_name, through:, source:) ⇒ Object
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
# File 'lib/wormy/associatable.rb', line 62 def has_one_through(association_name, through:, source:) define_method(association_name) do = self.class.[through] = .model_class.[source] source_table = .table_name through_table = .table_name key_value = self.send(.foreign_key) results = WORMY::DBConnection.execute(<<-SQL, key_value) SELECT #{source_table}.* FROM #{through_table} JOIN #{source_table} ON #{through_table}.#{.foreign_key} = #{source_table}.#{.primary_key} WHERE #{through_table}.#{.primary_key} = ? SQL .model_class.parse_all(results).first end end |