在Rails 4.2.0之前,ActiveRecord会自动将String转换为所指定的类型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
在Rails 4.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
我在文档changelog中找不到此文件。是否已删除这种类型的字符串到数组转换,还是一个错误?在我的用例中,我从分配给模型的参数中获得了这样的字符串。它可以在Rails 4.1.10中工作,但在Rails 4.2.1中它会提高ActiveRecord::SerializationTypeMismatch
。
我不确定4.1.10和4.2.1之间的哪个提交引入了此行为,但这不是bug,因为在此处已对其进行了详细记录。特别是,
如果指定了class_name,则序列化的对象在分配和检索时必须属于该类。否则,将引发SerializationTypeMismatch。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句