Created
November 23, 2016 14:51
-
-
Save nplusp/4e2e2f2aef6367da9ddba305e3b51d81 to your computer and use it in GitHub Desktop.
Hashes in params
This file contains hidden or 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
# 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