Skip to content

Instantly share code, notes, and snippets.

@dhnaranjo
Last active November 22, 2022 14:49
Show Gist options
  • Save dhnaranjo/96c9f57637b465141b1f425891e4b718 to your computer and use it in GitHub Desktop.
Save dhnaranjo/96c9f57637b465141b1f425891e4b718 to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
require 'bundler/inline'
gemfile do
gem 'rails'
gem 'debug'
end
require 'rails/all'
require 'minitest/autorun'
require 'debug'
# Given a submitted field with the name `user[things_attributes][UNIQUE_KEY][name]`
# Sub UNIQUE_KEY for the index of the particular field being rendered, or its ID,
# or whatever so long as that key is an integer.
class StrongParamsTest < ActiveSupport::TestCase
def expected
[
ActionController::Parameters.new({ 'name' => 'Table' }).permit(:name),
ActionController::Parameters.new({ 'name' => 'Pat' }).permit(:name)
]
end
def permitted_things_attributes(params)
ActionController::Parameters
.new(params)
.require(:user)
.permit(things_attributes: [:name])
.fetch(:things_attributes)
.values
end
# Passes, uses index for unique key.
test 'strong params with integer-able keys' do
raw_params = {
user: {
things_attributes: {
'1' => { name: 'Table' },
'2' => { name: 'Pat' }
}
}
}
assert_equal expected, permitted_things_attributes(raw_params)
end
# Failing, uses non-unique index
test 'strong params with non-unique integer-able keys' do
raw_params = {
user: {
things_attributes: {
'1' => { name: 'Table' },
'1' => { name: 'Pat' }
}
}
}
assert_equal expected, permitted_things_attributes(raw_params)
end
# Failing, showing using a UUID if that's what you got
test 'strong params with non-integer-able keys' do
raw_params = {
user: {
things_attributes: {
'96883cfc-0b3a-4946-81d7-cbdfddd36f9c' => { name: 'Table' },
'572070ad-cf9e-404f-8342-50eefc6cbda3' => { name: 'Pat' }
}
}
}
assert_equal expected, permitted_things_attributes(raw_params)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment