ActiveRecord 不会将字符串中的数组转换为数组
ActiveRecord does not convert array in string to array
在 Rails 4.2.0 之前,ActiveRecord 会自动将字符串转换为 serialize
指定的类型。
class Post < ActiveRecord::Base
serialize :options, Array # Column type: 'text', DB: PostgreSQL
end
class PostTest < ActiveSupport::TestCase
test "assign options" do
post = Post.new
post.options = "[1,2,3]" # => "[1,2,3]"
end
end
在Rails4.2.1
class Post < ActiveRecord::Base
serialize :options, Array
end
class PostTest < ActiveSupport::TestCase
test "assign options" do
post = Post.new
post.options = "[1,2,3]" # ActiveRecord::SerializationTypeMismatch: Attribute was supposed to be a Array, but was a String.
end
end
我在文档和变更日志中找不到这个。这种类型的字符串到数组的转换是否被删除或者是一个错误?在我的用例中,我有一个来自分配给模型的参数的字符串。它在 Rails 4.1.10 中有效,但在 Rails 4.2.1 中它会引发 ActiveRecord::SerializationTypeMismatch
.
这很奇怪,因为 YAMLColumn 多年来一直表现得像这样。看看this commit.
我不确定 4.1.10 和 4.2.1 之间的哪个提交引入了此行为,但它不是错误,因为它有据可查 here。特别是,
If class_name is specified, the serialized object must be of that class on assignment and retrieval. Otherwise SerializationTypeMismatch will be raised.
在 Rails 4.2.0 之前,ActiveRecord 会自动将字符串转换为 serialize
指定的类型。
class Post < ActiveRecord::Base
serialize :options, Array # Column type: 'text', DB: PostgreSQL
end
class PostTest < ActiveSupport::TestCase
test "assign options" do
post = Post.new
post.options = "[1,2,3]" # => "[1,2,3]"
end
end
在Rails4.2.1
class Post < ActiveRecord::Base
serialize :options, Array
end
class PostTest < ActiveSupport::TestCase
test "assign options" do
post = Post.new
post.options = "[1,2,3]" # ActiveRecord::SerializationTypeMismatch: Attribute was supposed to be a Array, but was a String.
end
end
我在文档和变更日志中找不到这个。这种类型的字符串到数组的转换是否被删除或者是一个错误?在我的用例中,我有一个来自分配给模型的参数的字符串。它在 Rails 4.1.10 中有效,但在 Rails 4.2.1 中它会引发 ActiveRecord::SerializationTypeMismatch
.
这很奇怪,因为 YAMLColumn 多年来一直表现得像这样。看看this commit.
我不确定 4.1.10 和 4.2.1 之间的哪个提交引入了此行为,但它不是错误,因为它有据可查 here。特别是,
If class_name is specified, the serialized object must be of that class on assignment and retrieval. Otherwise SerializationTypeMismatch will be raised.