Module: ModelX::Associations::ClassMethods
- Defined in:
- lib/model_x/associations.rb
Instance Method Summary collapse
-
#belongs_to(association, options = {}) ⇒ Object
Define a belongs_to association.
-
#has_many(association, options = {}) ⇒ Object
Defines a has_many association.
Instance Method Details
#belongs_to(association, options = {}) ⇒ Object
Define a belongs_to association.
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/model_x/associations.rb', line 19 def belongs_to(association, = {}) class_name = [:class_name] || association.to_s.camelize foreign_key = [:foreign_key] || "#{association}_id" attribute foreign_key # Define attribute readers and writers for the ID attribute. class_eval "\n def \#{foreign_key}\n read_attribute(:\#{foreign_key}) || @\#{association}.try(:id)\n end\n\n def \#{foreign_key}=(value)\n value = nil if value.blank?\n write_attribute :\#{foreign_key}, value\n @\#{association} = nil\n end\n\n def \#{association}(reload = false)\n id = \#{foreign_key}\n if reload\n @\#{association} = ::\#{class_name}.find_by_id(id) if id\n else\n @\#{association} ||= ::\#{class_name}.find_by_id(id) if id\n end\n end\n\n def \#{association}=(value)\n value = nil if value.blank?\n @\#{association} = value\n write_attribute :\#{foreign_key}, nil\n end\n\n RUBY\n\nend\n", __FILE__, __LINE__+1 |
#has_many(association, options = {}) ⇒ Object
Defines a has_many association.
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 |
# File 'lib/model_x/associations.rb', line 58 def has_many(association, = {}) attribute association class_name = [:class_name] || association.to_s.singularize.camelize foreign_key = [:foreign_key] || "#{association.to_s.singularize}_id" ids_attribute = foreign_key.pluralize attribute ids_attribute # Define attribute readers and writers for the ID attribute. class_eval "\n def \#{ids_attribute}\n read_attribute(:\#{ids_attribute}) || read_attribute(:\#{association}).try(:id)\n end\n\n def \#{ids_attribute}=(value)\n value = nil if value.blank?\n write_attribute :\#{ids_attribute}, value\n @\#{association} = nil\n end\n\n def \#{association}(reload = false)\n ids = \#{ids_attribute}\n if reload\n @\#{association} = ::\#{class_name}.where(:id => ids) if ids\n else\n @\#{association} ||= ::\#{class_name}.where(:id => ids) if ids\n end\n end\n\n def \#{association}=(value)\n value = nil if value.blank?\n @\#{association} = value\n write_attribute :\#{ids_attribute}, nil\n end\n\n RUBY\n\nend\n", __FILE__, __LINE__+1 |