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



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/findable/associations/active_record_ext.rb', line 43

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
    define_method("#{name}_with_findable_polymorphic") do
      begin
        public_send("#{name}_without_findable_polymorphic")
      rescue NotActiveRecord
        id = public_send("#{name}_id")
        public_send("#{name}_type").constantize.find(id)
      end
    end
    alias_method_chain name.to_sym, :findable_polymorphic
  end
end

#has_many(*args) ⇒ Object



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

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



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

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