【问题标题】:Custom wrap JSON to Virtus Model?自定义包装 JSON 到 Virtus 模型?
【发布时间】:2017-08-29 16:11:06
【问题描述】:

我有一个如下所示的 JSON 对象:

{  
   "id":"10103",
   "key":"PROD",
   "name":"Product",
   "projectCategory":{  
      "id":"10000",
      "name":"design",
      "description":""
   }
}

还有一个如下所示的 Virtus 模型:

class Project
  include Virtus.model

  attribute  :id, Integer 
  attribute  :key, String
  attribute  :name, String

  attribute  :category, String  #should be the value of json["projectCategory"]["name"]

end

除了尝试将 Project.category 映射到 json["projectCategory"]["name"] 之外,一切都很好。

所以我要寻找的最终 Virtus 对象应该如下所示:

"id"       => "10103",
"key"      => "PROD",
"name"     => "Product",
"category" => "design"

现在我正在使用 Project.new(JSON.parse(response)) 或基本上是 json 响应的哈希创建一个模型实例。如何自定义将 Virtus 的一些属性映射到我的 json 响应?

【问题讨论】:

    标签: ruby-on-rails models virtus


    【解决方案1】:

    所以我最终发现您可以覆盖 self.new 方法,从而允许您获取传递给 Virtus 模型的哈希值中的嵌套值。

    我最终做了以下工作正常:

    class Project
      include Virtus.model
    
      attribute  :id,       Integer 
      attribute  :name,     String
      attribute  :key,      String
      attribute  :category, String
    
      def self.new(attributes)
        new_attributes = attributes.dup
    
        # Map nested obj "projectCategory.name" to Project.category
        if attributes.key?("projectCategory") and attributes["projectCategory"].key?("name")
          new_attributes[:'category'] = attributes["projectCategory"]["name"]
        end
    
        super(new_attributes)
      end
    
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-29
      • 2015-09-24
      • 1970-01-01
      • 1970-01-01
      • 2014-10-05
      • 1970-01-01
      相关资源
      最近更新 更多