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
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 |
# File 'lib/associations/associations.rb', line 94 def belongs_to(association_id, = {}) = { :class_name => association_id.to_s.classify, :foreign_key => association_id.to_s.foreign_key }.merge() field [:foreign_key].to_sym define_method(association_id) do [:class_name].constantize.find_by_id(send([:foreign_key])) end define_method("#{association_id}=") do |new_value| attributes[[:foreign_key].to_sym] = new_value ? new_value.id : nil end end |
#has_many(association_id, options = {}) ⇒ Object
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
# File 'lib/associations/associations.rb', line 58 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 }.merge() klass = [:class_name].constantize if ActiveRecord.const_defined?(:Relation) && klass.all.class < ActiveRecord::Relation klass.where([:foreign_key] => id) elsif klass.respond_to?(:scoped) klass.scoped(:conditions => {[:foreign_key] => id}) else klass.send("find_all_by_#{[:foreign_key]}", id) end end end |
#has_one(association_id, options = {}) ⇒ Object
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
# File 'lib/associations/associations.rb', line 78 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 |