Created
April 24, 2010 20:21
-
-
Save steam/377918 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# <product> | |
# <orders> | |
# <order> | |
# <amount>1</amount> | |
# </order> | |
# <order> | |
# <amount>1</amount> | |
# </order> | |
# </orders> | |
# </product> | |
# | |
# becomes | |
# | |
# <product> | |
# <orders-attributes> | |
# <amount>1</amount> | |
# </orders-attributes> | |
# <orders-attributes> | |
# <amount>1</amount> | |
# </orders-attributes> | |
# </product> | |
def fix_from_xml_nested_assocations klass, p | |
# Get all the associations for the model | |
klass.reflect_on_all_associations(:has_many).each do |association| | |
a = association.name.to_s | |
# If the parameters include this association key | |
if p.has_key? a | |
# The association should contain the singular form of the key | |
unless p[a][a.singularize].nil? | |
# If there are multiple records, this will contain an array | |
if p[a][a.singularize].is_a? Array | |
# Move the data into the relevant key | |
p[a + "_attributes"] = p[a][a.singularize] | |
# If there is only one record, this will contain a hash of that record | |
elsif p[a][a.singularize].is_a? Hash | |
# We need to put the hash into an array to make it work properly | |
p[a + "_attributes"] = [p[a][a.singularize]] | |
end | |
# Delete the original key | |
p.delete a | |
end | |
end | |
end | |
# Return the fixed params | |
p | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment