17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
# File 'lib/polymorphic_belongs_to.rb', line 17
def polymorphic_belongs_to(name, types:, validate_types: true, **options)
name = name.to_sym
self.polymorphic_belongs_to_types ||= {}
polymorphic_belongs_to_types[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) }
inclusion_options = validate_types.is_a?(Hash) ? validate_types : {in: types.map(&:name)}
validates(foreign_type, inclusion: inclusion_options, allow_nil: !presence_required)
end
end
|