I’m trying to have two documents one for posts and one for replies, and connect them using “Referenced 1-N” relationship.
From what I read from the mongoid documentation, all you have to do is add has_many and belongs_to into both classes and mongoid will allow me to add child documents that points to the parent.
So what I want to do simply is
- create a new reply document that points to the parent
- if possible have an array that holds ids of the children
I’ve tried to access reply from post in all ways and it doesn’t work. So it would be great if someone can crack this puzzle for me 🙂
Output
undefined method ‘reply’ for #< PostsController: >
Model
class Post
include Mongoid::Document
has_many :replies
field :text,:type => String
end
class Reply
include Mongoid::Document
belongs_to :post
field :name, :type => String
field :text, :type => String
end
Controller
def create_reply
post = Post.find(params[:post_id])
post.reply.new(params[:post])
end
replyis undefined for yourPostclass becausePosthas manyreplies, notreply.Try writing
post.replies.new(params[:post])in yourcreate_replymethod instead.