Module: Associatable

Included in:
ModelBase
Defined in:
lib/reloj/orm/associatable.rb,
lib/reloj/orm/associatable2.rb

Instance Method Summary collapse

Instance Method Details

#assoc_optionsObject



63
64
65
# File 'lib/reloj/orm/associatable.rb', line 63

def assoc_options
  @assoc_options ||= {}
end

#belongs_to(name, options = {}) ⇒ Object



47
48
49
50
51
52
53
54
# File 'lib/reloj/orm/associatable.rb', line 47

def belongs_to(name, options = {})
  assoc_options[name] = options = BelongsToOptions.new(name, options)
  define_method(name) do
    foreign_key_value = send(options.foreign_key)
    model_class = options.model_class
    model_class.where(options.primary_key => foreign_key_value).first
  end
end

#has_many(name, options = {}) ⇒ Object



56
57
58
59
60
61
# File 'lib/reloj/orm/associatable.rb', line 56

def has_many(name, options = {})
  options = HasManyOptions.new(name, self.name, options)
  define_method(name) do
    options.model_class.where( options.foreign_key => id )
  end
end

#has_one_through(name, through_name, source_name) ⇒ Object

Remember to go back to 04_associatable to write ::assoc_options



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/reloj/orm/associatable2.rb', line 6

def has_one_through(name, through_name, source_name)
  self_options = assoc_options[name]
  through_options = assoc_options[through_name]
  #very close to finishing
  define_method(name) do
    # p all your assoc_options keys/values
    source_options = through_options.model_class.assoc_options[source_name]
    source_table = source_options.table_name
    through_table = through_options.table_name
    x = DBConnection.execute(<<-SQL)
      SELECT
        #{source_table}.*
      FROM
        #{source_table}
      INNER JOIN
        #{through_table}
      ON
        #{source_table}.id = #{through_table}.#{source_options.foreign_key}
      INNER JOIN
        #{self.class.table_name}
      ON
        #{self.class.table_name}.#{through_options.foreign_key} = #{through_table}.id;
    SQL

    source_options.model_class.parse_all(x).first
    # use constantize
  end
end