0

我是 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
4

1 回答 1

1

Mongoid 为您的关系提供访问器,在这种情况下

posts.comments
posts.comments = [ Comment.new ]
comment.post
comment.post = Post.new
post.comments << Comment.new
post.comments.push(Comment.new)
...

请参阅, http: //mongoid.org/docs/relations/embedded/1-n.html

这是修改后的帖子/显示操作。

  def show

    @post = Post.find(params[:id])
    @comment = @post.comments.all.to_a
    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @post }
    end

  end

这是一个新的帖子/评论操作。

  def comment
    @post = Post.find(params[:id])
    comment = Comment.create(params[:comment])
    @post.comments << comment
    @comment = @post.comments.all.to_a

    respond_to do |format|
      format.html { render :action => "show" }
      format.xml  { render :xml => @post }
    end
  end

app/views/posts/show.html.erb

<pre>
Post
  <%= @post.inspect %>
Comments
  <%= @comment.inspect %>
</pre>

测试/功能/posts_controller_test.rb

require 'test_helper'

class PostsControllerTest < ActionController::TestCase

  def setup
    Post.delete_all
    Comment.delete_all
    @param = {
        post: { title: 'Mongoid relations', body: 'The relation has auto-generated methods' },
        comment: { content: 'a piece of cake' }
    }
  end

  test "show" do
    post = Post.create(@param[:post])
    get :show, id: post.id
    assert_response(:success)
  end

  test "new" do
    get :new
    assert_response(:success)
  end

  test "create" do
    get :create, @param
    assert_response(:success)
  end

  test "comment" do
    post = Post.create(@param[:post])
    get :comment, { id: post.id }.merge(@param)
    assert_response(:success)
    assert_equal(1, Post.count)
    assert_equal(1, Comment.count)
    assert_equal(@param[:comment][:content], Post.first.comments.first.content)
  end

end
于 2012-05-17T16:43:41.573 回答