Ruby on rails 将JSON自定义包装到Virtus模型?

Ruby on rails 将JSON自定义包装到Virtus模型?,ruby-on-rails,models,virtus,Ruby On Rails,Models,Virtus,我有一个JSON对象,如下所示: { "id":"10103", "key":"PROD", "name":"Product", "projectCategory":{ "id":"10000", "name":"design", "description":"" } } class Project include Virtus.model attribute :id, Integer attribut

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

{  
   "id":"10103",
   "key":"PROD",
   "name":"Product",
   "projectCategory":{  
      "id":"10000",
      "name":"design",
      "description":""
   }
}
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
以及一个如下所示的Virtus模型:

{  
   "id":"10103",
   "key":"PROD",
   "name":"Product",
   "projectCategory":{  
      "id":"10000",
      "name":"design",
      "description":""
   }
}
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响应?

因此我最终发现,您可以覆盖
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

因此,我最终发现您可以覆盖
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