【问题标题】:Saving child objects when parsing foreign nested JSON objects in Mongoid and Rails在 Mongoid 和 Rails 中解析外部嵌套 JSON 对象时保存子对象
【发布时间】:2012-02-23 19:01:24
【问题描述】:

我正在将社交媒体发布从 REST API 存储到 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 可以,但我想知道...

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

【问题讨论】:

    标签: ruby-on-rails json activerecord associations mongoid


    【解决方案1】:

    你不能使用accepts_nested_attributes_for吗?

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

    【讨论】:

    • 对不起,我不知道“accept_nested_attributes_for”到底是做什么的,在查看了它的作用(直接为孩子赋值)之后,这似乎是我需要的。谢谢!! manas.com.ar/spalladino/2010/03/03/…
    猜你喜欢
    • 1970-01-01
    • 2020-07-07
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 2015-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多