module Associatable
Public Instance Methods
assoc_options()
click to toggle source
# File lib/easy_save/associatable.rb, line 78 def assoc_options @assoc ||= {} end
belongs_to(name, options = {})
click to toggle source
# 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 = {})
click to toggle source
# 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)
click to toggle source
# 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 = <<-SQL SELECT #{source_options.table_name}.* FROM #{through_options.table_name} JOIN #{source_options.table_name} ON #{through_options.table_name}.#{source_options.send(:foreign_key)} = #{source_options.table_name}.#{source_options.send(:primary_key)} WHERE #{through_options.table_name}.#{through_options.send(:primary_key)} SQL res = DBConnection.execute(sql) source_options.model_class.new(res.first) end end