# frozen_string_literal: true module JsonApiToolbox module Postable class << self def normalize_post(hash, model) associations = model.reflect_on_all_associations.map(&:name) normalized_hash = hash.map do |key, value| child_model = association_class(model, key) if value.is_a? Hash key = associations.include?(key.to_sym) ? "#{key}_attributes" : key hash_value = check_child_association(value, key, model, child_model) [key, hash_value] end Hash[normalized_hash] end private def association_class(model, key) association = model.reflect_on_all_associations.find do |association_i| association_i.name.to_s == key.to_s end return false unless association class_name = (association.options.symbolize_keys[:class_name] || key) ActiveSupport::Inflector.singularize(class_name).camelize.constantize end def check_child_association(value, key, model, child_model) if value.is_a?(Hash) && !model.has_attribute?(key) normalize_post(value, child_model) else value end end end end end