Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# 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
You can’t perform that action at this time.