Module: Associatable

Included in:
Puffs::SQLObject
Defined in:
lib/sql_object/associatable.rb

Instance Method Summary collapse

Instance Method Details

#assoc_optionsObject



65
66
67
# File 'lib/sql_object/associatable.rb', line 65

def assoc_options
  @assoc_options ||= {}
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, options = {})
  options = BelongsToOptions.new(name, options)
  assoc_options[name] = options

  define_method(name) do
    foreign_key_value = self.send(options.foreign_key)
    return nil if foreign_key_value.nil?

    options.model_class
           .where(options.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, options = {})
  options = HasManyOptions.new(name, self.to_s, options)
  assoc_options[name] = options

  define_method(name) do
    target_key_value = self.send(options.primary_key)
    return nil if target_key_value.nil?
    options.model_class
           .where(options.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_options = assoc_options[through_name]
  define_method(name) do
    through_fk = through_options.foreign_key
    through_class = through_options.model_class
    key_val = self.send(through_options.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_options = assoc_options[through_name]

  define_method(name) do
    source_options =
      through_options.model_class.assoc_options[source_name]
    through_pk = through_options.primary_key
    key_val = self.send(through_options.foreign_key)

    source_options.model_class.includes(through_options.model_class)
                              .where(through_pk => key_val).first
  end
end