Module: Associatable

Included in:
LarisrecordBase
Defined in:
lib/laris/larisrecord/associatable.rb

Instance Method Summary collapse

Instance Method Details

#assoc_optionsObject



67
68
69
# File 'lib/laris/larisrecord/associatable.rb', line 67

def assoc_options
  @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, options = {})
  options = BelongsToOptions.new(assoc_name, options)
  assoc_options[assoc_name] = options

  define_method(assoc_name) do
    klass = options.model_class
    foreign_key_value = send(options.foreign_key)
    primary_key = options.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, options = {})
  options = HasManyOptions.new(assoc_name, self.name, options)

  define_method(assoc_name) do
    klass = options.model_class
    foreign_key = options.foreign_key
    primary_key_value = send(options.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_options = assoc_options[through_name]
    through_klass = through_options.model_class
    through_table = through_klass.table_name
    through_fk_value = send(through_options.foreign_key)
    through_pk = through_options.primary_key

    source_options = through_klass.assoc_options[source_name]
    source_klass = source_options.model_class
    source_table = source_klass.table_name
    source_fk = source_options.foreign_key
    source_pk = source_options.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