Guest User

Untitled

a guest
Jun 20th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.41 KB | None | 0 0
  1. class ApplicationController < ActionController::Base
  2. private
  3.  
  4. def fix_nested_attribute_structure(data = nil, model = nil)
  5. unless data
  6. # guess data based on current controller
  7. data = params[self.class.to_s.sub('Controller', '').singularize.underscore.to_sym]
  8. end
  9. unless model
  10. # guess model based on current controller
  11. model = self.class.to_s.sub('Controller', '').singularize.constantize
  12. end
  13.  
  14. # iterate over the nested attribute keys for the given model
  15. model.nested_attributes_options.keys.each do |key|
  16. # skip if current data-set doesn't contain this key
  17. next unless data.has_key? key
  18.  
  19. # When recieving the XML all nested attributes are "doubble-nested".
  20. # We need to remove this doubble-nesting and also ensure that the
  21. # content is wrapped inside an array (e.g. if the orignal XML only
  22. # contained a single sub-node, the XML->Hash conversion would not
  23. # have done this)
  24. raise "More than one sub-key found inside a nested attribute key" if data[key].keys.size > 1
  25. sub_key = data[key].keys[0]
  26. data[key] = [ data[key].delete(sub_key) ].flatten
  27.  
  28. # Recursively fix nested attributes
  29. fix_nested_attribute_structure data[key], eval(key.to_s.classify)
  30.  
  31. # Renamed the nested attribute name by appending '_attributes' to
  32. # the key-name
  33. data["#{key.to_s}_attributes".to_sym] = data.delete(key)
  34. end
  35. end
  36. end
Add Comment
Please, Sign In to add comment