提交 d569d0ba 编写于 作者: S Sean Griffin

PG arrays should type cast user input

We guarantee that `model.value` does not change after
`model.save && model.reload`. This requires type casting user input for
non-string types.
上级 9a0c2e5c
......@@ -12,12 +12,16 @@ def initialize(subtype)
def type_cast_from_database(value)
if value.is_a?(::String)
type_cast_array(parse_pg_array(value))
type_cast_array(parse_pg_array(value), :type_cast_from_database)
else
super
end
end
def type_cast_from_user(value)
type_cast_array(value, :type_cast_from_user)
end
# Loads pg_array_parser if available. String parsing can be
# performed quicker by a native extension, which will not create
# a large amount of Ruby objects that will need to be garbage
......@@ -32,11 +36,11 @@ def type_cast_from_database(value)
private
def type_cast_array(value)
def type_cast_array(value, method)
if value.is_a?(::Array)
value.map { |item| type_cast_array(item) }
value.map { |item| type_cast_array(item, method) }
else
@subtype.type_cast_from_database(value)
@subtype.public_send(method, value)
end
end
end
......
......@@ -97,8 +97,13 @@ def test_type_cast_array
def test_type_cast_integers
x = PgArray.new(ratings: ['1', '2'])
assert x.save!
assert_equal(['1', '2'], x.ratings)
assert_equal([1, 2], x.ratings)
x.save!
x.reload
assert_equal([1, 2], x.ratings)
end
def test_select_with_strings
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册