Module: Associatable

Included in:
SQLObject
Defined in:
lib/easy_save/associatable.rb

Instance Method Summary collapse

Instance Method Details

#assoc_optionsObject



78
79
80
# File 'lib/easy_save/associatable.rb', line 78

def assoc_options
  @assoc ||= {}
end

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



51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/easy_save/associatable.rb', line 51

def belongs_to(name, options = {})
  options = BelongsToOptions.new(name.to_s, options)
  self.assoc_options[name] = options

  define_method(name) do
    fk_method = options.send(:foreign_key)
    fk_id = self.send(fk_method)

    class_name = options.class_name.constantize

    res = class_name.where(id: fk_id)
    res.first || nil
  end
end

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



66
67
68
69
70
71
72
73
74
75
76
# File 'lib/easy_save/associatable.rb', line 66

def has_many(name, options = {})
  options = HasManyOptions.new(name.to_s, self.to_s, options)

  define_method(name) do
    pk_id = self.id
    fk_id = options.send(:foreign_key)

    class_name = options.class_name.constantize
    class_name.where("#{fk_id}": pk_id)
  end
end

#has_one_through(name, through_name, source_name) ⇒ Object



83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/easy_save/associatable.rb', line 83

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] 

    sql = "    SELECT\n      \#{source_options.table_name}.* \n    FROM\n      \#{through_options.table_name} \n    JOIN\n      \#{source_options.table_name} \n    ON\n      \#{through_options.table_name}.\#{source_options.send(:foreign_key)} \n      = \#{source_options.table_name}.\#{source_options.send(:primary_key)} \n    WHERE\n      \#{through_options.table_name}.\#{through_options.send(:primary_key)}\n    SQL\n\n    res = DBConnection.execute(sql)\n    source_options.model_class.new(res.first)\n  end\nend\n"