Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/68.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 on rails 在Mongoid和Rails中解析外部嵌套JSON对象时保存子对象_Ruby On Rails_Json_Activerecord_Associations_Mongoid - Fatal编程技术网

Ruby on rails 在Mongoid和Rails中解析外部嵌套JSON对象时保存子对象

Ruby on rails 在Mongoid和Rails中解析外部嵌套JSON对象时保存子对象,ruby-on-rails,json,activerecord,associations,mongoid,Ruby On Rails,Json,Activerecord,Associations,Mongoid,我正在将社交媒体帖子从RESTAPI存储到Mongoid 我使用的是非常基本的用户/帖子模型: class Post include Mongoid::Document belongs_to :user end # post class User include Mongoid::Document has_many :posts end # post 现在假设从API检索到的解析JSON对象是: hash = { "id"

我正在将社交媒体帖子从RESTAPI存储到Mongoid

我使用的是非常基本的用户/帖子模型:

   class Post
     include Mongoid::Document
     belongs_to :user
   end # post

   class User
     include Mongoid::Document
     has_many :posts
   end # post
现在假设从API检索到的解析JSON对象是:

hash = {
  "id" : "7890",
  "text": "I ate foo bar tonight",
  "user": {
     "id" : "123",
     "name" : "beavis"
   }
}
   p = Post.new(hash)
   p.save
这将对象另存为:

   {
      "id" : "7890",
      "text": "I ate foo bar tonight",
      "user_id": "123"
    }
现在我该如何保存用户对象呢?p、 user.save将起作用,但我想知道

  • 我必须检查用户对象是否已经在mongodb中。我正在使用User.find(p.User.id)。但是User.find()是否只查找ID?或者find()是否也加载整个用户对象
  • 我正在重写Post.create()方法以立即执行此操作。那么糟糕吗
  • 保存子对象的最佳位置是什么?我是否在Post.create()中检查用户是否存在?Post.before_create()?Post.after_create()?还是别的什么
  • p.user.save和user.create(p.user)有区别吗

  • 您不能将接受\u嵌套的\u属性\u用于

    class Post
      include Mongoid::Document
      belongs_to :user
      accept_nested_attributes_for :user
    end # post
    

    抱歉,我不知道“accept_nested_attributes_for”的确切功能,在查找它的功能(将值直接分配给子对象)后,它似乎就是我所需要的。谢谢