Module: Associatable
- Included in:
- TGauge::TRecordBase
- Defined in:
- lib/app/models/associatable.rb
Instance Method Summary collapse
- #assoc_options ⇒ Object
-
#belongs_to(name, options = {}) ⇒ Object
Phase IIIb.
- #has_many(name, options = {}) ⇒ Object
- #has_one(name, options = {}) ⇒ Object
- #through(name, through_name, source_name) ⇒ Object
Instance Method Details
#assoc_options ⇒ Object
114 115 116 |
# File 'lib/app/models/associatable.rb', line 114 def @assoc_options ||= {} end |
#belongs_to(name, options = {}) ⇒ Object
Phase IIIb
36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/app/models/associatable.rb', line 36 def belongs_to(name, = {}) = BelongsToOptions.new(name, ) define_method(name) do fkey_val = self.send(.foreign_key) class_obj = .model_class class_obj.where(.primary_key => fkey_val).first end [name] = end |
#has_many(name, options = {}) ⇒ Object
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/app/models/associatable.rb', line 49 def has_many(name, = {}) # ... unless .first[0] == :through = HasManyOptions.new(name, self.to_s, ) define_method(name) do class_obj = .model_class pr_key = self.send(.primary_key) class_obj.where(.foreign_key => pr_key) end [name] = else [:source] ||= name through(name, [:through], [:source]) end end |
#has_one(name, options = {}) ⇒ Object
109 110 111 112 |
# File 'lib/app/models/associatable.rb', line 109 def has_one (name, = {}) [:source] ||= name through(name, [:through], [:source]) end |
#through(name, through_name, source_name) ⇒ Object
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 |
# File 'lib/app/models/associatable.rb', line 67 def through(name, through_name, source_name) define_method(name) do = self.class.[through_name] = .model_class.[source_name] if .is_a?(BelongsToOptions) # A to B has a belongs_to relationship a_test_key = self.send(.foreign_key) b_column = .primary_key else # A to B has a has_many relationship a_test_key = self.send(.primary_key) b_column = .foreign_key end if .is_a?(BelongsToOptions) # B to C has a belongs_to relationship b_test_key = .foreign_key c_column = .primary_key else # B to C has a has_many relationship b_test_key = .primary_key c_column = .foreign_key end source_table = .table_name through_table = .table_name all_data = DBConnection.execute(<<-SQL) SELECT #{source_table}.* FROM #{through_table} JOIN #{source_table} ON #{source_table}.#{c_column} = #{through_table}.#{b_test_key} WHERE #{through_table}.#{b_column} = #{a_test_key} SQL .model_class.parse_all(all_data) end end |