Module: Associatable
- Included in:
- LarisrecordBase
- Defined in:
- lib/laris/larisrecord/associatable.rb
Instance Method Summary collapse
- #assoc_options ⇒ Object
- #belongs_to(assoc_name, options = {}) ⇒ Object
- #has_many(assoc_name, options = {}) ⇒ Object
- #has_one_through(assoc_name, through_name, source_name) ⇒ Object
Instance Method Details
#assoc_options ⇒ Object
67 68 69 |
# File 'lib/laris/larisrecord/associatable.rb', line 67 def @assoc_options ||= {} end |
#belongs_to(assoc_name, options = {}) ⇒ Object
42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/laris/larisrecord/associatable.rb', line 42 def belongs_to(assoc_name, = {}) = BelongsToOptions.new(assoc_name, ) [assoc_name] = define_method(assoc_name) do klass = .model_class foreign_key_value = send(.foreign_key) primary_key = .primary_key klass.where(primary_key => foreign_key_value).first end end |
#has_many(assoc_name, options = {}) ⇒ Object
55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/laris/larisrecord/associatable.rb', line 55 def has_many(assoc_name, = {}) = HasManyOptions.new(assoc_name, self.name, ) define_method(assoc_name) do klass = .model_class foreign_key = .foreign_key primary_key_value = send(.primary_key) klass.where(foreign_key => primary_key_value) end end |
#has_one_through(assoc_name, through_name, source_name) ⇒ Object
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 |
# File 'lib/laris/larisrecord/associatable.rb', line 71 def has_one_through(assoc_name, through_name, source_name) define_method(assoc_name) do = [through_name] through_klass = .model_class through_table = through_klass.table_name through_fk_value = send(.foreign_key) through_pk = .primary_key = through_klass.[source_name] source_klass = .model_class source_table = source_klass.table_name source_fk = .foreign_key source_pk = .primary_key result = DBConnection.execute(<<-SQL, through_fk_value) SELECT #{source_table}.* FROM #{through_table} JOIN #{source_table} ON #{through_table}.#{source_fk} = #{source_table}.#{source_pk} WHERE #{through_table}.#{through_pk} = ? SQL source_klass.new(result.first) end end |