Module: Bartleby::Associatable
- Included in:
- Objectifier
- Defined in:
- lib/bartleby/associatable.rb
Instance Method Summary collapse
- #assoc_options ⇒ Object
- #belongs_to(name, options = {}) ⇒ Object
- #has_many(name, options = {}) ⇒ Object
- #has_one_through(name, through_name, source_name) ⇒ Object
Instance Method Details
#assoc_options ⇒ Object
115 116 117 |
# File 'lib/bartleby/associatable.rb', line 115 def @assoc_options ||= {} end |
#belongs_to(name, options = {}) ⇒ Object
50 51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/bartleby/associatable.rb', line 50 def belongs_to(name, = {}) = BelongsToOptions.new(name, ) [name] = define_method(name) do foreign_key = send(.foreign_key) target_class = .model_class conditions = {.primary_key => foreign_key} target_class.where(conditions).first end end |
#has_many(name, options = {}) ⇒ Object
63 64 65 66 67 68 69 70 71 72 |
# File 'lib/bartleby/associatable.rb', line 63 def has_many(name, = {}) = HasManyOptions.new(name, self.name, ) define_method(name) do target_class = .model_class primary_key = send(.primary_key) conditions = {.foreign_key => primary_key} target_class.where(conditions) end end |
#has_one_through(name, through_name, source_name) ⇒ Object
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 |
# File 'lib/bartleby/associatable.rb', line 74 def has_one_through(name, through_name, source_name) define_method(name) do = self.class.[through_name] = .model_class.[source_name] fk1 = .foreign_key pk1 = .primary_key fk2 = .foreign_key pk2 = .primary_key t1 = self.class.table_name t2 = .table_name t3 = .table_name first_join_conditions = "#{t1}.#{fk1} = #{t2}.#{pk1}" second_join_conditions = "#{t2}.#{fk2} = #{t3}.#{pk2}" primary_key = .primary_key query_string = <<-SQL SELECT #{t3}.* FROM #{t1} JOIN #{t2} ON #{first_join_conditions} JOIN #{t3} ON #{second_join_conditions} WHERE #{t1}.#{primary_key} = ? SQL result = Connection.execute(query_string, self.id) result.empty? ? nil : .model_class.new(result.first) end end |