Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save u007/8d5f71d9fc2c3fc0a942fa848e5888e3 to your computer and use it in GitHub Desktop.
Save u007/8d5f71d9fc2c3fc0a942fa848e5888e3 to your computer and use it in GitHub Desktop.
# ruby
res = params.require(:table).permit(:field1,
table_sub_table_attributes: [:key_field_id, :id, :_destroy])
res[:table_sub_table_attributes] = reduce_params(res[:table_sub_table_attributes], :key_field_id)
# reduce delete to delete existing which is not selected
# and insert only when is not an existing
# does not handle updating existing (which is not used)
def reduce_params(attributes, key_field)
res = []
retain = []
attributes.each do |row|
# only append destroy if no new record found
if row[:_destroy]
# existing destroy
del = true
attributes.each do |inner_row|
if !inner_row[:_destroy] && row[key_field] == inner_row[key_field]
# found insert, means don't delete
del = false
break
end
end # inner loop
if !del
retain << row[key_field] # ignoring
else
res << row # append for deletion
end
elsif !row[:id]
# only append new record if not an existing
if !retain.include?(row[key_field])
res << row
end
# insert or existing
end
end # outer loop
# Rails.logger.info "in: #{attributes.inspect}, \n result: #{res.inspect}"
res
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment