Rails: ActionController::Parameters sliced with symbol keys returns hash with string keys

Created on 5 Feb 2019  路  1Comment  路  Source: rails/rails

Steps to reproduce

# frozen_string_literal: true

require "bundler/inline"

gemfile(true) do
  source "https://rubygems.org"

  git_source(:github) { |repo| "https://github.com/#{repo}.git" }

  gem "rails", "~> 5.1.0" # github: "rails/rails"
end

require "action_controller"
require "action_pack"
require "minitest/autorun"

class BugTest < Minitest::Test
  extend Minitest::Spec::DSL

  let(:params) do
    ActionController::Parameters.new("test" => "value").permit(:test)
  end

  def test_indifferent_access
    assert params["test"] == "value"
    assert params[:test] == "value"
  end

  def test_basic_hash_slicing
    h = { "test" => "value", test: "value_sym_key" }
    assert h.slice("test") == { "test" => "value" }
    assert h.slice(:test) == { test: "value_sym_key" }
  end

  def test_slice_with_string_key
    assert params.slice("test") == { "test" => "value" }
  end

  # This should not fail
  def test_slice_with_sym_key
    assert params.slice(:test) == { test: "value" }
  end

  def test_slice_with_sym_key_workaround
    assert params.slice(:test).to_h.symbolize_keys == { test: "value" }
  end
end

Expected behavior

Slicing from ActionController::Parameters with symbol keys should return a hash with the requested symbol keys.

Actual behavior

Slicing from ActionController::Parameters with symbol keys returns a hash with string keys.

Workaround

Call to_h.symbolize_keys on returned hash.

System configuration

Rails version: 5.1.6.1, 5.2.2, 6.0.0.beta1

Ruby version: 2.5.1p57

>All comments

Thank you for the issue. This is the intended behavior. Slice works in the same way as to_h.slice. It always return hashes with string keys, never symbols.

Was this page helpful?
0 / 5 - 0 ratings