Ruby on rails 在Mongoid和Rails中解析外部嵌套JSON对象时保存子对象
我正在将社交媒体帖子从RESTAPI存储到Mongoid 我使用的是非常基本的用户/帖子模型: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"
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将起作用,但我想知道
您不能将接受\u嵌套的\u属性\u用于
class Post
include Mongoid::Document
belongs_to :user
accept_nested_attributes_for :user
end # post
抱歉,我不知道“accept_nested_attributes_for”的确切功能,在查找它的功能(将值直接分配给子对象)后,它似乎就是我所需要的。谢谢