Module: WhalesORM::Associatable

Included in:
Base
Defined in:
lib/associatable.rb

Instance Method Summary collapse

Instance Method Details

#assoc_optionsObject



70
71
72
# File 'lib/associatable.rb', line 70

def assoc_options
  @assoc_options ||= {}
end

#belongs_to(name, options = {}) ⇒ Object



43
44
45
46
47
48
49
50
51
52
# File 'lib/associatable.rb', line 43

def belongs_to(name, options = {})
  opts = WhalesORM::BelongsToOptions.new(name.to_s, options)

  define_method(name) do
    foreign_key = send(opts.foreign_key)
    opts.model_class.where(opts.primary_key => foreign_key).first
  end

  assoc_options[name] = opts
end

#has_many(name, options = {}) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/associatable.rb', line 54

def has_many(name, options = {})
  if options[:through]
    has_one_or_many_through(name, options[:through], options[:source])
  else
    opts = WhalesORM::HasManyOptions.new(name.to_s, self.to_s, options)

    define_method(name) do
      primary_key_value = send(opts.primary_key)
      where_clause = {opts.foreign_key => primary_key_value}
      opts.model_class.where(where_clause)
    end

    assoc_options[name] = opts
  end
end

#has_one_through(name, through_name, source_name) ⇒ Object



74
75
76
77
78
79
80
# File 'lib/associatable.rb', line 74

def has_one_through(name, through_name, source_name)
  # unless [through_options, source_options].all? { |opt| opt.is_a?(BelongsToOptions) }
  #   raise "has_one_through must use two belongs_to relations!"
  # end

    has_one_or_many_through(name, through_name, source_name, one: true)
end