Use Storext (or just Virtus) with nested array or hash objects

流过昼夜 提交于 2021-02-19 05:32:18

问题


I have a postgres DB backing my Rails app with a class with a jsonb column

class Product < AR::B
  include Storext.model(data: {})

  store_attributes :data do
    thing_one String
    thing_two Boolean # Not actually showing up in the `data` hash
    foos      FooCollection[Foo]
  end
end

class FooCollection < Array
  def <<(obj)
    if Hash
      super(Coupon.new(obj)
    else
      # Other coersions
    end
  end
end

class Foo
  include Storext.model

  attribute :id,                Integer
  attribute :price,             Float
  attribute :regular_price,     Float
end

But Foo in the terminal is returning undefined method after_initialize for Foo:Class

Is there a way to nest Storext models the same way it is with Virtus? And if so is there an idiomatic way to add validations on the nested classes? (Abandoning Storext, and a pure Virtus solution would also answer the question)

Maybe this is an A/B problem because I just included Virtus in FooCollection and it also disappeared from the data hash (which I consider weird since Storext is based on Virtus and can accept Virtus methods).


回答1:


Storext was created to type-cast simple values only. I haven't played around storing complex objects in Virtus myself, and I'm still undecided whether or not that should be part of Storext. While it uses Virtus in the background, I don't think it should implement everything Virtus can do.

A little late to the party, but I hope this helps.



来源:https://stackoverflow.com/questions/36926927/use-storext-or-just-virtus-with-nested-array-or-hash-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!