我是 Rails 和 mongo 的新手。我正在尝试构建一个简单的博客页面,其中一篇文章可以包含许多评论。后控制器是我有问题的地方。我不知道如何存储和检索已发布帖子的评论。
后模型
class Post
include Mongoid::Document
field :title, :type => String
field :body, :type => String
has_many :comments
end
评论模型
class Comment
include Mongoid::Document
field :content, :type => String
belongs_to :post
end
当前的帖子控制器可以保存帖子但不能评论。
class PostsController < ApplicationController
def show
@post = Post.find(params[:id])
@comment=Comment.new
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @post }
end
end
def new
@post = Post.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @post }
end
end
def create
@post = Post.new(params[:post])
respond_to do |format|
if @post.save
format.html { redirect_to(@post, :notice => 'Post was successfully created.') }
format.xml { render :xml => @post, :status => :created, :location => @post }
else
format.html { render :action => "new" }
format.xml { render :xml => @post.errors, :status => :unprocessable_entity }
end
end
end