Module: Associatable
- Included in:
- Puffs::SQLObject
- Defined in:
- lib/sql_object/associatable.rb
Instance Method Summary collapse
- #assoc_options ⇒ Object
- #belongs_to(name, options = {}) ⇒ Object
- #has_many(name, options = {}) ⇒ Object
- #has_many_through(name, through_name, source_name) ⇒ Object
- #has_one_through(name, through_name, source_name) ⇒ Object
Instance Method Details
#assoc_options ⇒ Object
65 66 67 |
# File 'lib/sql_object/associatable.rb', line 65 def ||= {} end |
#belongs_to(name, options = {}) ⇒ Object
38 39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/sql_object/associatable.rb', line 38 def belongs_to(name, = {}) = BelongsToOptions.new(name, ) [name] = define_method(name) do foreign_key_value = self.send(.foreign_key) return nil if foreign_key_value.nil? .model_class .where(.primary_key => foreign_key_value) .first end end |
#has_many(name, options = {}) ⇒ Object
52 53 54 55 56 57 58 59 60 61 62 63 |
# File 'lib/sql_object/associatable.rb', line 52 def has_many(name, = {}) = HasManyOptions.new(name, self.to_s, ) [name] = define_method(name) do target_key_value = self.send(.primary_key) return nil if target_key_value.nil? .model_class .where(.foreign_key => target_key_value) .to_a end end |
#has_many_through(name, through_name, source_name) ⇒ Object
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 |
# File 'lib/sql_object/associatable.rb', line 83 def has_many_through(name, through_name, source_name) = [through_name] define_method(name) do through_fk = .foreign_key through_class = .model_class key_val = self.send(.primary_key) #2 queries, we could reduce to 1 by writing Puffs::SQLRelation.join. through_class.where(through_fk => key_val) .includes(source_name) .load .included_relations .first .to_a end end |
#has_one_through(name, through_name, source_name) ⇒ Object
69 70 71 72 73 74 75 76 77 78 79 80 81 |
# File 'lib/sql_object/associatable.rb', line 69 def has_one_through(name, through_name, source_name) = [through_name] define_method(name) do = .model_class.[source_name] through_pk = .primary_key key_val = self.send(.foreign_key) .model_class.includes(.model_class) .where(through_pk => key_val).first end end |