Module: Bartleby::Associatable

Included in:
Objectifier
Defined in:
lib/bartleby/associatable.rb

Instance Method Summary collapse

Instance Method Details

#assoc_optionsObject



115
116
117
# File 'lib/bartleby/associatable.rb', line 115

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

  assoc_options[name] = options

  define_method(name) do
    foreign_key = send(options.foreign_key)
    target_class = options.model_class
    conditions = {options.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, options = {})
  options = HasManyOptions.new(name, self.name, options)

  define_method(name) do
    target_class = options.model_class
    primary_key = send(options.primary_key)
    conditions = {options.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
    through_options = self.class.assoc_options[through_name]
    source_options = through_options.model_class.assoc_options[source_name]

    fk1 = through_options.foreign_key
    pk1 = through_options.primary_key

    fk2 = source_options.foreign_key
    pk2 = source_options.primary_key

    t1 = self.class.table_name
    t2 = through_options.table_name
    t3 = source_options.table_name

    first_join_conditions = "#{t1}.#{fk1} = #{t2}.#{pk1}"
    second_join_conditions = "#{t2}.#{fk2} = #{t3}.#{pk2}"
    primary_key = through_options.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 : source_options.model_class.new(result.first)
  end
end