Skip to content

Instantly share code, notes, and snippets.

@johncant
Created July 22, 2013 17:58
Show Gist options
  • Save johncant/6056036 to your computer and use it in GitHub Desktop.
Save johncant/6056036 to your computer and use it in GitHub Desktop.
This simple controller mixin allows you to lose the "_attributes" suffix when POST/PUTting data to your API, while maintaining the same nested attribute model behaviour. Simply replace params[:posts] with attributify(:posts) in your controllers. The old behaviour should still work.
module Attributify
def attributify(key, unprocessed=params[key])
if unprocessed.is_a? Hash
specific_params = {}
unprocessed.each do |k,v|
if (v.is_a?(Hash) && !k.to_s.match(/_attributes$/)) or (v.is_a?(Array) && !k.to_s.match(/_ids$/))
# Nested, so suffix with '_attributes'
specific_params["#{k}_attributes".to_sym] = attributify(key, v)
else
specific_params[k] = v
end
end
return specific_params
elsif unprocessed.is_a? Array
unprocessed.map do |p| attributify(key, p) end
else
unprocessed
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment