Module: ActiveHash::Associations::Methods
- Defined in:
- lib/associations/associations.rb
Instance Method Summary collapse
- #belongs_to(association_id, options = {}) ⇒ Object
- #has_many(association_id, options = {}) ⇒ Object
- #has_one(association_id, options = {}) ⇒ Object
Instance Method Details
#belongs_to(association_id, options = {}) ⇒ Object
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 |
# File 'lib/associations/associations.rb', line 134 def belongs_to(association_id, = {}) = { :class_name => association_id.to_s.classify, :foreign_key => association_id.to_s.foreign_key, :primary_key => "id" }.merge() field [:foreign_key].to_sym define_method(association_id) do [:class_name].constantize.send("find_by_#{[:primary_key]}", send([:foreign_key])) end define_method("#{association_id}=") do |new_value| attributes[[:foreign_key].to_sym] = new_value ? new_value.send([:primary_key]) : nil end end |
#has_many(association_id, options = {}) ⇒ Object
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 |
# File 'lib/associations/associations.rb', line 95 def has_many(association_id, = {}) define_method(association_id) do = { :class_name => association_id.to_s.classify, :foreign_key => self.class.to_s.foreign_key, :primary_key => self.class.primary_key }.merge() klass = [:class_name].constantize primary_key_value = send([:primary_key]) foreign_key = [:foreign_key].to_sym if Object.const_defined?(:ActiveRecord) && ActiveRecord.const_defined?(:Relation) && klass < ActiveRecord::Relation klass.where(foreign_key => primary_key_value) elsif klass.respond_to?(:scoped) klass.scoped(:conditions => {foreign_key => primary_key_value}) else klass.where(foreign_key => primary_key_value) end end end |
#has_one(association_id, options = {}) ⇒ Object
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 |
# File 'lib/associations/associations.rb', line 118 def has_one(association_id, = {}) define_method(association_id) do = { :class_name => association_id.to_s.classify, :foreign_key => self.class.to_s.foreign_key }.merge() scope = [:class_name].constantize if scope.respond_to?(:scoped) && [:conditions] scope = scope.scoped(:conditions => [:conditions]) end scope.send("find_by_#{[:foreign_key]}", id) end end |