I’m storing social media postings from a REST API to Mongoid.
I’m using the very basic User/Post model:
class Post
include Mongoid::Document
belongs_to :user
end # post
class User
include Mongoid::Document
has_many :posts
end # post
Now let say the parsed JSON object retrieved from the API is:
hash = {
"id" : "7890",
"text": "I ate foo bar tonight",
"user": {
"id" : "123",
"name" : "beavis"
}
}
p = Post.new(hash)
p.save
This will save the object as:
{
"id" : "7890",
"text": "I ate foo bar tonight",
"user_id": "123"
}
Now how do I go about saving the user object too? p.user.save will work, but I want to know…
- I’ll have to check for the user object is already in mongodb or not. I’m using User.find(p.user.id). But does User.find() only look for the ID? Or does find() also load the whole user object?
- I’m overriding the Post.create() method to do this right now. Is that bad?
- What is the best place to save child objects? Do I check for user existence in Post.create()? Post.before_create()? Post.after_create()? Or something else?
- Is there a difference with p.user.save and User.create(p.user)??
Can’t you use accepts_nested_attributes_for?