Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 无法从JSON创建正确的Mongoid模型_Ruby_Json_Mongoid_Mongoid4 - Fatal编程技术网

Ruby 无法从JSON创建正确的Mongoid模型

Ruby 无法从JSON创建正确的Mongoid模型,ruby,json,mongoid,mongoid4,Ruby,Json,Mongoid,Mongoid4,我试图从相应的JSON结构创建一个Mongoid模型 但是,它不包括嵌入式关系框架。 我正在使用Mongoid 4.0。我是做错了什么还是这是一个错误 如果我通过store_以与默认序列化不同的名称存储任何嵌入关系,它将按预期工作。另外,如果我在数据库中从JSON创建模型,而不是初始化它,那么一切都很好 JSON输入 模型 测试应用程序 require'json' require“require\u relative” 需要相对的“供应商” 开始 json=json.parse(File.rea

我试图从相应的JSON结构创建一个Mongoid模型

但是,它不包括嵌入式关系框架。 我正在使用Mongoid 4.0。我是做错了什么还是这是一个错误

如果我通过store_以与默认序列化不同的名称存储任何嵌入关系,它将按预期工作。另外,如果我在数据库中从JSON创建模型,而不是初始化它,那么一切都很好

JSON输入

模型

测试应用程序

require'json'
require“require\u relative”
需要相对的“供应商”
开始
json=json.parse(File.read('input.json'))
@profile=Vendor.new(json)
放置@profile.inspect
rescue JSON::ParserError=>e

puts“Error:“将您的JSON格式发送为,{”供应商“{”名称“:“MyName”,“frameworks_属性“:[{”名称“:“grails”,“runtime:“groovy”,“versions:[]}}}}我不能这样做,JSON是固定的。您的创建方法在哪里存储到数据库中!!!此时我不想将其存储在DB中,只想通过
@profile=Vendor.new(json)
{
  "name": "MyName",
  "frameworks": [
    {
      "name": "grails",
      "runtime": "groovy",
      "versions": []
    }
  ]
}
require 'mongoid'

class Vendor
  include Mongoid::Document
    include Mongoid::Attributes::Dynamic

  # fields
  field :name, type: String
  # relations
  embeds_many :frameworks
  # validations
  validates :name, presence: true
  validates :frameworks, presence: true
end

class Framework
  include Mongoid::Document

  embedded_in :vendor

  field :name, type: String
  field :runtime, type: String
  field :versions, type: Array
  # validations
  validates :name, presence: true
  validates :runtime, presence: true
end
require 'json'
require 'require_relative'
require_relative 'vendor'

begin
  json = JSON.parse(File.read('input.json'))
  @profile = Vendor.new(json)
  puts @profile.inspect
rescue JSON::ParserError => e
  puts "Error: " << e.to_s
end