Module: ActiveRepository::Associations::Methods
- Defined in:
- lib/active_repository/associations.rb
Overview
:nodoc:
Instance Method Summary collapse
-
#belongs_to(association_id, options = {}) ⇒ Object
Defines “belongs to” type relation between ActiveRepository objects.
-
#has_many(association_id, options = {}) ⇒ Object
Defines “has many” type relation between ActiveRepository objects.
-
#has_one(association_id, options = {}) ⇒ Object
Defines “has one” type relation between ActiveRepository objects.
Instance Method Details
#belongs_to(association_id, options = {}) ⇒ Object
Defines “belongs to” type relation between ActiveRepository objects
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 |
# File 'lib/active_repository/associations.rb', line 79 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 klass = [:class_name].constantize id = send([:foreign_key]) if id.present? object = klass.find_by_id(id) else nil end end define_method("#{association_id}=") do |new_value| attributes.delete(association_id.to_sym) send("#{[:foreign_key]}=", (new_value.try(:id) ? new_value.id : new_value)) end end |
#has_many(association_id, options = {}) ⇒ Object
Defines “has many” type relation between ActiveRepository objects
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/active_repository/associations.rb', line 42 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 objects = [] if klass.respond_to?(:scoped) objects = klass.scoped(:conditions => {[:foreign_key] => id}) else objects = klass.send("find_all_by_#{[:foreign_key]}", id) end end end |
#has_one(association_id, options = {}) ⇒ Object
Defines “has one” type relation between ActiveRepository objects
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
# File 'lib/active_repository/associations.rb', line 61 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 |