Module: Associatable

Included in:
MonoRM::Base
Defined in:
lib/monorm/associatable.rb

Instance Method Summary collapse

Instance Method Details

#assoc_optionsObject



62
63
64
65
# File 'lib/monorm/associatable.rb', line 62

def assoc_options
  @assoc_options ||= {}
  @assoc_options
end

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



37
38
39
40
41
42
43
44
45
46
# File 'lib/monorm/associatable.rb', line 37

def belongs_to(name, options = {})
  self.assoc_options[name] = MonoRM::BelongsToOptions.new(name, options)
  define_method(name) do
    belongs_options = self.class.assoc_options[name]
    foreign_key = send(belongs_options.foreign_key)
    model_class = belongs_options.class_name.constantize

    model_class.where(belongs_options.primary_key => foreign_key).first
  end
end

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



48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/monorm/associatable.rb', line 48

def has_many(name, options = {})

  self.assoc_options[name] = MonoRM::HasManyOptions.new(name, self.name, options)

  define_method(name) do
    has_many_options = self.class.assoc_options[name]
    primary_key = send(has_many_options.primary_key)
    model_class = has_many_options.class_name.constantize

    model_class.where(has_many_options.foreign_key => primary_key)
  end
end

#has_one_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
# File 'lib/monorm/associatable.rb', line 67

def has_one_through(name, through_name, source_name)


  define_method(name) do
    through_options = self.class.assoc_options[through_name]
    source_options = through_options.model_class.assoc_options[source_name]

    through_options_table = through_options.table_name
    through_options_foreign_key = through_options.foreign_key
    through_options_primary_key = through_options.primary_key

    source_options_table = source_options.table_name
    source_options_foreign_key = source_options.foreign_key
    source_options_primary_key = source_options.primary_key


    search_key = self.send(through_options_foreign_key)
    has_one_results = MonoRM::DBConnection.execute(<<-SQL, search_key)
      SELECT
        #{source_options_table}.*
      FROM
        #{through_options_table}
      JOIN
        #{source_options_table}
      ON
        #{source_options_table}.#{source_options_primary_key} = #{through_options_table}.#{source_options_foreign_key}

      WHERE
        #{through_options_table}.#{through_options_primary_key} = INTERPOLATOR_MARK

    SQL

    source_options.model_class.parse_all(has_one_results).first
  end
end