diff --git a/activemodel/lib/active_model/serialization.rb b/activemodel/lib/active_model/serialization.rb index 40cdc971d4a37..17a5854854c2c 100644 --- a/activemodel/lib/active_model/serialization.rb +++ b/activemodel/lib/active_model/serialization.rb @@ -128,7 +128,9 @@ def serializable_hash(options = nil) return serializable_attributes(attribute_names) if options.blank? if only = options[:only] - attribute_names &= Array(only).map(&:to_s) + only = Array(only).map(&:to_s) + attribute_names &= only + attribute_names = attribute_names.in_order_of(:itself, only, filter: false) elsif except = options[:except] attribute_names -= Array(except).map(&:to_s) end diff --git a/activemodel/test/cases/serialization_test.rb b/activemodel/test/cases/serialization_test.rb index 4eaef06c79659..bc40ca0d4fecf 100644 --- a/activemodel/test/cases/serialization_test.rb +++ b/activemodel/test/cases/serialization_test.rb @@ -62,6 +62,11 @@ def test_method_serializable_hash_should_work_with_only_option assert_equal expected, @user.serializable_hash(only: [:name]) end + def test_method_serializable_hash_should_work_with_only_option_with_order_of_given_keys + expected = { "name" => "David", "email" => "david@example.com" } + assert_equal expected.keys, @user.serializable_hash(only: [:name, :email]).keys + end + def test_method_serializable_hash_should_work_with_except_option expected = { "gender" => "male", "email" => "david@example.com" } assert_equal expected, @user.serializable_hash(except: [:name])