mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-25 07:16:49 +00:00
Merge pull request #1629 from lawitschka/key-transform-on-deserialization
Properly deserialize dasherized keys
This commit is contained in:
@@ -155,7 +155,7 @@ module ActiveModelSerializers
|
||||
|
||||
# @api private
|
||||
def parse_attributes(attributes, options)
|
||||
attributes
|
||||
transform_keys(attributes, options)
|
||||
.map { |(k, v)| { field_key(k, options) => v } }
|
||||
.reduce({}, :merge)
|
||||
end
|
||||
@@ -182,23 +182,29 @@ module ActiveModelSerializers
|
||||
prefix_key = field_key(assoc_name, options).to_s.singularize
|
||||
hash =
|
||||
if assoc_data.is_a?(Array)
|
||||
{ "#{prefix_key}_ids".to_sym => assoc_data.map { |ri| ri['id'] } }
|
||||
{ "#{prefix_key}_ids".to_sym => assoc_data.map { |ri| ri[:id] } }
|
||||
else
|
||||
{ "#{prefix_key}_id".to_sym => assoc_data ? assoc_data['id'] : nil }
|
||||
{ "#{prefix_key}_id".to_sym => assoc_data && assoc_data.is_a?(Hash) ? assoc_data[:id] : nil }
|
||||
end
|
||||
|
||||
polymorphic = (options[:polymorphic] || []).include?(assoc_name.to_sym)
|
||||
hash["#{prefix_key}_type".to_sym] = assoc_data['type'] if polymorphic
|
||||
hash["#{prefix_key}_type".to_sym] = assoc_data[:type] if polymorphic
|
||||
|
||||
hash
|
||||
end
|
||||
|
||||
# @api private
|
||||
def parse_relationships(relationships, options)
|
||||
relationships
|
||||
.map { |(k, v)| parse_relationship(k, v['data'], options) }
|
||||
transform_keys(relationships, options)
|
||||
.map { |(k, v)| parse_relationship(k, v[:data], options) }
|
||||
.reduce({}, :merge)
|
||||
end
|
||||
|
||||
# @api private
|
||||
def transform_keys(hash, options)
|
||||
transform = options[:key_transform] || :underscore
|
||||
KeyTransform.send(transform, hash)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -32,6 +32,16 @@ module ActiveModelSerializers
|
||||
hash.deep_transform_keys! { |key| key.to_s.dasherize.to_sym }
|
||||
end
|
||||
|
||||
# Transforms keys to underscore.
|
||||
# This is the default case for deserialization in the JsonApi adapter.
|
||||
#
|
||||
# @example:
|
||||
# "some-key" => "some_key",
|
||||
# @see {https://github.com/rails/rails/blob/master/activesupport/lib/active_support/inflector/methods.rb#L89-L98 ActiveSupport::Inflector.underscore}
|
||||
def underscore(hash)
|
||||
hash.deep_transform_keys! { |key| key.to_s.underscore.to_sym }
|
||||
end
|
||||
|
||||
# Returns the hash unaltered
|
||||
def unaltered(hash)
|
||||
hash
|
||||
|
||||
Reference in New Issue
Block a user