提交 2f8c596d 编写于 作者: S Sean Griffin

Maintain a consistent order in `ActiveRecord::Base#attributes`

Fixes #18871
上级 d89912b9
......@@ -20,7 +20,7 @@ def build_from_database(values = {}, additional_types = {})
end
class LazyAttributeHash # :nodoc:
delegate :select, :transform_values, :each_key, to: :materialize
delegate :transform_values, :each_key, to: :materialize
def initialize(types, values, additional_types)
@types = types
......@@ -50,6 +50,16 @@ def initialize_dup(_)
super
end
def select
keys = types.keys | values.keys | delegate_hash.keys
keys.each_with_object({}) do |key, hash|
attribute = self[key]
if yield(key, attribute)
hash[key] = attribute
end
end
end
protected
attr_reader :types, :values, :additional_types, :delegate_hash
......
......@@ -65,6 +65,16 @@ class AttributeSetTest < ActiveRecord::TestCase
assert_equal({ foo: 1, bar: 2.2 }, attributes.to_h)
end
test "to_hash maintains order" do
builder = AttributeSet::Builder.new(foo: Type::Integer.new, bar: Type::Float.new)
attributes = builder.build_from_database(foo: '2.2', bar: '3.3')
attributes[:bar]
hash = attributes.to_h
assert_equal [[:foo, 2], [:bar, 3.3]], hash.to_a
end
test "values_before_type_cast" do
builder = AttributeSet::Builder.new(foo: Type::Integer.new, bar: Type::Integer.new)
attributes = builder.build_from_database(foo: '1.1', bar: '2.2')
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册