Module: PolymorphicBelongsTo::ClassMethods

Defined in:
lib/polymorphic_belongs_to.rb

Instance Method Summary collapse

Instance Method Details

#polymorphically_belongs_to(name, types:, validate_types: true, **options) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/polymorphic_belongs_to.rb', line 17

def polymorphically_belongs_to(name, types:, validate_types: true, **options)
  name = name.to_sym

  self.defined_polymorphic_belongs_tos ||= {}
  defined_polymorphic_belongs_tos[name.to_s] = types

  belongs_to(name, polymorphic: true, **options)

  if validate_types
    foreign_type = reflect_on_association(name).foreign_type.to_sym
    presence_required = validators_on(name).any? { |v| v.is_a?(ActiveRecord::Validations::PresenceValidator) }

    validates(foreign_type, inclusion: {in: types.map(&:name)}, allow_nil: !presence_required)
  end
end