Virtus是否支持Hash属性[SomeKey =>阵列[CustomModel]]?

时间:2016-02-18 20:44:31

标签: ruby-on-rails ruby virtus

例如:

class Nested
  include Virtus.model

  attribute :name, String
end

class Base
  # Does not raise an exception even though the array failed to coerce!
  include Virtus.model(:strict => true)

  attribute :name, String
  attribute :nested, Nested
  attribute :array , Array[Nested]
  attribute :hash, Hash[String => Nested]
  attribute :hash_array_int, Hash[String => Array[Integer]]
  attribute :hash_array, Hash[String => Array[Nested]]  # attribute in question!
end

如果我尝试创建这样的对象:

a = Nested.new(name: "a")
b = Base.new(
  name: "b",
  nested: { name: "nested b" },
  array: [{ name: "array 1" }, { name: "array 2" }],
  hash: { "key": { name: "hash b" } },
  hash_array_int: { "key": [1, 2, 3] },
  hash_array: {
    # The below fails to coerce the objects in the array
    "key": [{ name: "hash_array 1"}, { name: "hash_array 2" }]
  }
)

每个属性都有效,除了Array[Nested]:hash_array的强制,给我堆栈跟踪:

NoMethodError: undefined method `call' for nil:NilClass
    from /.rvm/gems/ruby-2.2.4/gems/virtus-1.0.5/lib/virtus/attribute.rb:104:in `coerce'
    from /.rvm/gems/ruby-2.2.4/gems/virtus-1.0.5/lib/virtus/attribute/collection.rb:79:in `block in coerce'
    from /.rvm/gems/ruby-2.2.4/gems/virtus-1.0.5/lib/virtus/attribute/collection.rb:78:in `each'
    from /.rvm/gems/ruby-2.2.4/gems/virtus-1.0.5/lib/virtus/attribute/collection.rb:78:in `each_with_object'
    from /.rvm/gems/ruby-2.2.4/gems/virtus-1.0.5/lib/virtus/attribute/collection.rb:78:in `coerce'
    from /.rvm/gems/ruby-2.2.4/gems/virtus-1.0.5/lib/virtus/attribute/hash.rb:110:in `block in coerce'
    from /.rvm/gems/ruby-2.2.4/gems/virtus-1.0.5/lib/virtus/attribute/hash.rb:109:in `each'
    from /.rvm/gems/ruby-2.2.4/gems/virtus-1.0.5/lib/virtus/attribute/hash.rb:109:in `each_with_object'
    from /.rvm/gems/ruby-2.2.4/gems/virtus-1.0.5/lib/virtus/attribute/hash.rb:109:in `coerce'
    from /.rvm/gems/ruby-2.2.4/gems/virtus-1.0.5/lib/virtus/attribute/coercible.rb:14:in `set'
    from /.rvm/gems/ruby-2.2.4/gems/virtus-1.0.5/lib/virtus/attribute_set.rb:146:in `block in define_writer_method'
    from /.rvm/gems/ruby-2.2.4/gems/virtus-1.0.5/lib/virtus/attribute_set.rb:173:in `block in set'
    from /.rvm/gems/ruby-2.2.4/gems/virtus-1.0.5/lib/virtus/attribute_set.rb:170:in `each'
    from /.rvm/gems/ruby-2.2.4/gems/virtus-1.0.5/lib/virtus/attribute_set.rb:170:in `set'
    from /.rvm/gems/ruby-2.2.4/gems/virtus-1.0.5/lib/virtus/instance_methods.rb:17:in `initialize'
    from (irb):2:in `new'

所以看起来在https://github.com/solnic/virtus/blob/master/lib/virtus/attribute.rb#L104中没有正确创建coercer 通过 https://github.com/solnic/virtus/blob/master/lib/virtus/attribute/collection.rb#L79https://github.com/solnic/virtus/blob/master/lib/virtus/attribute/hash.rb#L110

在我开始使用自己的宝石进行调试之前,有没有人知道一个干净的解决方法,或者我是否正在尝试正确设置嵌套关系?

0 个答案:

没有答案