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
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 |
# File 'lib/associations/associations.rb', line 167 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].safe_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
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 |
# File 'lib/associations/associations.rb', line 124 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].safe_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 define_method("#{association_id.to_s.underscore.singularize}_ids") do public_send(association_id).map(&:id) end end |
#has_one(association_id, options = {}) ⇒ Object
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 |
# File 'lib/associations/associations.rb', line 150 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, :primary_key => self.class.primary_key }.merge() scope = [:class_name].safe_constantize if scope.respond_to?(:scoped) && [:conditions] scope = scope.scoped(:conditions => [:conditions]) end scope.send("find_by_#{[:foreign_key]}", send([:primary_key])) end end |