Module: Findable::Associations::ActiveRecordExt::ClassMethods

Defined in:
lib/findable/associations/active_record_ext.rb

Instance Method Summary collapse

Instance Method Details

#belongs_to(*args) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/findable/associations/active_record_ext.rb', line 41

def belongs_to(*args)
  name, options = Utils.parse_args(args)
  model = Utils.model_for(name, safe: true, **options)

  if model && model < Findable::Base
    foreign_key = options[:foreign_key].presence || name.to_s.foreign_key

    define_method(name) do
      model.find_by(model.primary_key => public_send(foreign_key))
    end

    define_method("#{name}=") do |value|
      value = value ? value.public_send(model.primary_key) : nil
      public_send("#{foreign_key}=", value)
    end

    Utils.add_reflection(:belongs_to, name.to_sym, options, self)
  else
    super
  end
end

#has_many(*args) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/findable/associations/active_record_ext.rb', line 7

def has_many(*args)
  name, options = Utils.parse_args(args)
  model = Utils.model_for(name, collection: true, safe: true, **options)

  if model && model < Findable::Base
    foreign_key = options[:foreign_key].presence || model_name.name.foreign_key

    define_method(name) do
      model.where(foreign_key => public_send(self.class.primary_key))
    end

    Utils.add_reflection(:has_many, name.to_sym, options, self)
  else
    super
  end
end

#has_one(*args) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/findable/associations/active_record_ext.rb', line 24

def has_one(*args)
  name, options = Utils.parse_args(args)
  model = Utils.model_for(name, safe: true, **options)

  if model && model < Findable::Base
    foreign_key = options[:foreign_key].presence || model_name.name.foreign_key

    define_method(name) do
      model.find_by(foreign_key => public_send(self.class.primary_key))
    end

    Utils.add_reflection(:has_one, name.to_sym, options, self)
  else
    super
  end
end