Skip to content

Instantly share code, notes, and snippets.

@nplusp
Created November 23, 2016 14:51
Show Gist options
  • Save nplusp/4e2e2f2aef6367da9ddba305e3b51d81 to your computer and use it in GitHub Desktop.
Save nplusp/4e2e2f2aef6367da9ddba305e3b51d81 to your computer and use it in GitHub Desktop.
Hashes in params
# Hash in params
def product_params
properties_keys = params[:product].try(:fetch, :properties, {}).keys
params.require(:product).permit(:title, :description, properties: properties_keys)
end
# Nested hash in params
def item_params
params.require(:item).permit(values: permit_recursive_params(params[:item][:values]))
end
def permit_recursive_params(params)
params.map do |key, value|
if value.is_a?(Array)
{ key => [ permit_recursive_params(value.first) ] }
elsif value.is_a?(Hash) || value.is_a?(ActionController::Parameters)
{ key => permit_recursive_params(value) }
else
key
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment