2013-03-26 27 views
0

我想在博客应用程序中显示评论模型的评论和正文。但它没有显示。 这里是评论控制器的代码。评论不显示在轨道上的红宝石博客应用程序

class CommentsController < ApplicationController 

    http_basic_authenticate_with :name => "dhh", :password => "secret", :only => :destroy 

    def create 
    @post=Post.find(params[:post_id]) 
    @[email protected](params[:comments]) 
    redirect_to post_path(@post) 
    end 

    def destroy 
    @post = Post.find(params[:post_id]) 
    @comment = @post.comments.find(params[:id]) 
    @comment.destroy 
    redirect_to post_path(@post) 
    end 

    def check 
    @comment=Comment.all 
    end 
end 

//注释模型

class Comment < ActiveRecord::Base 
    belongs_to :post 
    attr_accessible :body, :commenter 
end 

//桩模型

class Post < ActiveRecord::Base 
    attr_accessible :content, :name, :title, :tags_attributes 

    validates :name, :presence=>true 
    validates :title, :presence=>true, 
        :length=>{:minimum=>5} 
    has_many :comments, :dependent=>:destroy 
    has_many :tags 

    accepts_nested_attributes_for :tags, :allow_destroy => :true, 
    :reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } } 
end 

//注释视图

<p> 
    <b>Commenter:</b> 
    <%= comment.commenter %> 
</p> 

<p> 
    <b>Comment:</b> 
    <%= comment.body %> 
</p> 

<p> 
    <%= link_to 'Destroy Comment', [comment.post, comment], 
       :confirm => 'Are you sure?', 
       :method => :delete %> 
</p> 

//后视图

<p id="notice"><%= notice %></p> 

<p> 
    <b>Name:</b> 
    <%= @post.name %> 
</p> 

<p> 
    <b>Title:</b> 
    <%= @post.title %> 
</p> 

<p> 
    <b>Content:</b> 
    <%= @post.content %> 
</p> 

<p> 
    <b>Tags:</b> 
    <%= join_tags(@post) %> 
</p> 

<h2>Comments</h2> 
<%= render @post.comments %> 

<h2>Add a comment:</h2> 
<%= render "comments/form" %> 

<br /> 
<%= link_to 'Edit Post', edit_post_path(@post) %> | 
<%= link_to 'Back to Posts', posts_path %> | 

请修复此问题。

+0

你正在渲染评论视图的行为,显示这个请求的代码... – 2013-03-26 06:27:25

+0

对不起,我没有得到你。请详细解释一下,因为我是Ruby on Rails的新手。 – lurch123 2013-03-26 09:39:50

+0

我的意思是评论控制器的显示动作。 – 2013-03-26 10:15:11

回答

0
<%= render @post.comments %> 

不正确。您必须渲染部分,而不是对象。

我认为您在views/comments中的评论视图名为show.html.erb。尝试这样的:

<%= @post.comments.map do |comment| %> 
    <%= render 'comments/show', comment: comment %> 
<%= end %> 

UPD:我的错误:它是正确的,在评论中的描述。

+0

Alex Teut,**@post.comments.map**会给你什么? – 2013-03-26 10:18:08

+0

如果您有部分'views/posts/_comment.html.erb','<%= render @ post.comments%>'是绝对合法的。它会[呈现集合](http://guides.rubyonrails.org/layouts_and_rendering.html#rendering-collections)。 – khustochka 2013-03-26 12:17:39

+0

@maximus,对帖子的评论进行迭代。 – 2013-03-26 13:51:59

0

哪个文件就是您所说的“评论视图”?要成为一个能够呈现一个集这样

<%= render @post.comments %> 

你需要一个注释模板的地方views/comments/_comment.html.erb

当然,你可以将其放入另一个部分,例如“的帖子/ _comment.html.erb`但随后你必须更明确:

<%= render :partial => 'posts/comment', :collection => @post.comments %> 

(心中有在文件名中的下划线,而不是在‘传递给渲染部分路径’)