Module: Vundabar::Associations

Included in:
BaseModel
Defined in:
lib/vundabar/orm/associations.rb

Instance Method Summary collapse

Instance Method Details

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



13
14
15
16
17
18
19
20
21
# File 'lib/vundabar/orm/associations.rb', line 13

def belongs_to(model_name, options = {})
  define_method(model_name) do
    class_name = model_name.to_s.singularize.capitalize
    model = options.fetch(:class_name, class_name).to_constant
    foreign_key = model_name.to_s.concat("_id")
    value = send(foreign_key)
    model.find_by(id: value)
  end
end

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



3
4
5
6
7
8
9
10
11
# File 'lib/vundabar/orm/associations.rb', line 3

def has_many(name, options = {})
  define_method(name) do
    class_name = name.to_s.singularize.capitalize
    model = options.fetch(:class_name, class_name).to_constant
    foreign_key_column = self.class.to_s.downcase + "_id"
    foreign_key = options.fetch(:foreign_key, foreign_key_column)
    model.where("#{foreign_key} LIKE ?", id)
  end
end