Module: Associatable
- Included in:
- SQLObject
- Defined in:
- lib/easy_save/associatable.rb
Instance Method Summary collapse
- #assoc_options ⇒ Object
- #belongs_to(name, options = {}) ⇒ Object
- #has_many(name, options = {}) ⇒ Object
- #has_one_through(name, through_name, source_name) ⇒ Object
Instance Method Details
#assoc_options ⇒ Object
78 79 80 |
# File 'lib/easy_save/associatable.rb', line 78 def @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, = {}) = BelongsToOptions.new(name.to_s, ) self.[name] = define_method(name) do fk_method = .send(:foreign_key) fk_id = self.send(fk_method) class_name = .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, = {}) = HasManyOptions.new(name.to_s, self.to_s, ) define_method(name) do pk_id = self.id fk_id = .send(:foreign_key) class_name = .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 = self.class.[through_name] = .model_class.[source_name] sql = <<-SQL SELECT #{.table_name}.* FROM #{.table_name} JOIN #{.table_name} ON #{.table_name}.#{.send(:foreign_key)} = #{.table_name}.#{.send(:primary_key)} WHERE #{.table_name}.#{.send(:primary_key)} SQL res = DBConnection.execute(sql) .model_class.new(res.first) end end |