自定义包装JSON到Virtus模型?

时间:2017-08-29 16:11:07

标签: ruby-on-rails models virtus

我有一个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响应?

1 个答案:

答案 0 :(得分:0)

所以我最终搞清楚你可以覆盖self.new方法,允许你在传递Virtus模型的哈希值中找到嵌套值。

我最终做了以下工作:#/ p>

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