Module: Associatable
- Included in:
- Bezel::BezelrecordBase
- Defined in:
- lib/bezelrecord_base/associatable.rb
Instance Method Summary collapse
- #assoc_options ⇒ Object
- #belongs_to(name, options = {}) ⇒ Object
- #has_many(name, options = {}) ⇒ Object
- #has_many_through(name, through_name, source_name) ⇒ Object
- #has_one_through(name, through_name, source_name) ⇒ Object
Instance Method Details
#assoc_options ⇒ Object
64 65 66 |
# File 'lib/bezelrecord_base/associatable.rb', line 64 def @prior_options ||= {} end |
#belongs_to(name, options = {}) ⇒ Object
38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/bezelrecord_base/associatable.rb', line 38 def belongs_to(name, = {}) = BelongsToOptions.new(name, ) @prior_options = @prior_options[name] = define_method(.class_name.downcase.to_sym) do foreign_key = send(.foreign_key) the_class = .model_class the_class.where(.primary_key => foreign_key).first end end |
#has_many(name, options = {}) ⇒ Object
50 51 52 53 54 55 56 57 58 59 60 61 62 |
# File 'lib/bezelrecord_base/associatable.rb', line 50 def has_many(name, = {}) = HasManyOptions.new(name, self, ) @prior_options = if @prior_options[name.to_s.singularize.to_sym].nil? @prior_options[name.to_s.singularize.to_sym] = else @prior_options[name.to_s.singularize.to_sym] << end define_method(.table_name.to_sym) do primary_key = send(.primary_key) .model_class.where(.foreign_key => primary_key) end end |
#has_many_through(name, through_name, source_name) ⇒ Object
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 |
# File 'lib/bezelrecord_base/associatable.rb', line 89 def has_many_through(name, through_name, source_name) define_method(name) do = self.class.[through_name] = .model_class.[source_name.to_s.singularize.to_sym] search_classes = .model_class.where(.foreign_key => send(.primary_key)) search_by = [] search_classes.each do |classes| search_by << classes.send(.primary_key) end results = DBConnection.execute(<<-SQL, *search_by) SELECT #{.table_name}.* FROM #{.table_name} JOIN #{.table_name} ON #{.table_name}.#{.foreign_key.to_s} = #{.table_name}.#{.primary_key.to_s} WHERE #{.table_name}.#{.primary_key} IN (#{Array.new(search_by.length,"?").join(", ")}) SQL results.map{|result| .model_class.new(result)} end end |
#has_one_through(name, through_name, source_name) ⇒ Object
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
# File 'lib/bezelrecord_base/associatable.rb', line 68 def has_one_through(name, through_name, source_name) define_method(name) do = self.class.[through_name] = .model_class.[source_name] search_by = send(.foreign_key) results = DBConnection.execute(<<-SQL, search_by) SELECT #{.table_name}.* FROM #{.table_name} JOIN #{.table_name} ON #{.table_name}.#{.primary_key.to_s} = #{.table_name}.#{.foreign_key.to_s} WHERE #{.table_name}.#{.primary_key} = ? SQL .model_class.new(results.first) end end |