Module: Associations
- Included in:
- BlocRecord::Base
- Defined in:
- lib/bloc_record/associations.rb
Instance Method Summary collapse
Instance Method Details
#belongs_to(association) ⇒ Object
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/bloc_record/associations.rb', line 23 def belongs_to(association) define_method(association) do association_name = association.to_s row = self.class.connection.get_first_row <<-SQL SELECT * FROM #{association_name} WHERE id = #{self.send(association_name + "_id")} SQL class_name = association_name.classify.constantize if row data = Hash[class_name.columns.zip(row)] class_name.new(data) end end end |
#has_many(association) ⇒ Object
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
# File 'lib/bloc_record/associations.rb', line 5 def has_many(association) define_method(association) do rows = self.class.connection.execute <<-SQL SELECT * FROM #{association.to_s.singularize} WHERE #{self.class.table}_id = #{self.id} SQL class_name = association.to_s.classify.constantize collection = BlocRecord::Collection.new rows.each do |row| collection << class_name.new(Hash[class_name.columns.zip(row)]) end collection end end |