Skip to content

Instantly share code, notes, and snippets.

@tlowrimore
Last active June 22, 2024 18:39
Show Gist options
  • Save tlowrimore/5ce1ad28d6599072506e to your computer and use it in GitHub Desktop.
Save tlowrimore/5ce1ad28d6599072506e to your computer and use it in GitHub Desktop.
Keeps your API lookin' good! No need for all that nested_attributes pollution in your request/response payloads
class V1::AddressBooksController < V1::BaseController
def create
@address_book = AddressBook.new address_book_params
unless @address_book.save
errors = @address_book.errors.to_hash(true)
render status: 422, json: { errors: errors }
end
end
private
def address_book_params
PrettyApi.with_nested_attributes pretty_address_book_params,
contacts: [:emails, :phones, :addresses]
end
def pretty_address_book_params
params.permit(
:device_install_id,
contacts: [
:local_id,
:first_name,
:last_name,
:nickname,
emails: [
:value,
:type
],
phones: [
:value,
:type
],
addresses: [
:type,
:street_address,
:city,
:state,
:postal_code,
:country
]
]
)
end
end
module PrettyApi
class << self
def with_nested_attributes(params, attrs)
return if params.blank?
case attrs
when Hash
with_nested_hash_attributes(params, attrs)
when Array
with_nested_array_attributes(params, attrs)
when String, Symbol
unless params[attrs].blank?
params["#{attrs}_attributes"] = params.delete attrs
end
end
params
end
private
def with_nested_hash_attributes(params, attrs)
attrs.each do |k, v|
with_nested_attributes params[k], v
with_nested_attributes params, k
end
end
def with_nested_array_attributes(params, attrs)
params.each do |np|
attrs.each do |v|
with_nested_attributes np, v
end
end
end
end
end
@jamesst20
Copy link

I wrote a gem recently that does something similar and push things even further :)

https://github.com/jamesst20/pretty_api

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment