2010-04-12 125 views
9

正如我总是键入的,我对rails和编程一般都很陌生,所以很简单。提前致谢。在Rails上创建博客ruby - 问题删除评论

我已经成功地遵循了Ryan Bates的初始教程how to build a weblog in 15 minutes。如果你不知道本教程将带你通过创建帖子并允许对这些帖子发表评论。它甚至通过在文章show.html.erb页面上创建并显示评论来引入AJAX。所有作品都很棒。

下面是打嗝,当Ryan带你到这个教程时,他清除了comments_controller,只显示了创建注释的代码。我正在尝试添加编辑和销毁注释的功能。似乎无法得到它的工作,不断删除实际的帖子不是评论(日志显示,我不断发送DELETE请求到PostsController)。这里是我的代码:

class CommentsController < ApplicationController 
def create 
    @post = Post.find(params[:post_id]) 
    @comment = @post.comments.create!(params[:comment]) 
    respond_to do |format| 
    format.html { redirect_to @post } 
    format.js 
    end 
end 

def destroy 
    @comment = Comment.find(params[:id]) 
    @comment.destroy 

    respond_to do |format| 
     format.html { redirect_to(posts_url) } 
     format.xml { head :ok } 
    end 
    end 
end 

/views/posts/show.html.erb

<%= render :partial => @post %> 

    <p> 
     <%= link_to 'Edit', edit_post_path (@post) %> | 
     <%= link_to 'Destroy', @post, :method => :delete, :confirm => "Are you sure?" %> | 
     <%= link_to 'See All Posts', posts_path %> 
    </p> 

    <h2>Comments</h2> 
    <div id="comments"> 
     <%= render :partial => @post.comments %> 
    </div> 

    <% remote_form_for [@post, Comment.new] do |f| %> 
     <p> 
      <%= f.label :body, "New Comment" %><br/> 
      <%= f.text_area :body %> 
     </p> 
     <p> 

<%= f.submit "Add Comment" %></p> 
<% end %> 

/views/comments/_comment.html.erb

<% div_for comment do %> 
    <p> 
     <strong>Posted <%= time_ago_in_words(comment.created_at) %> ago 
     </strong><br/> 
     <%= h(comment.body) %><br/> 
     <%= link_to 'Destroy', @comments, :method => :delete, :confirm => "Are you sure?" %> 
    </p> 
<% end %> 

的routes.rb

ActionController::Routing::Routes.draw do |map| 
    map.resources :posts, :has_many => :comments 
    map.connect ':controller/:action/:id' 
    map.connect ':controller/:action/:id.:format' 
end 
+0

“看不到它工作” - 你实际上试图解决它的是什么? – fig 2010-04-12 03:30:16

+0

我试着将comment.html.erb中的link_to改为@comment,comment,comments等。我还试着通过改变@comment = Comment.find(params [:id])来改变CommentsController的行为包括@ post.comment.destroy(params [:comment_id])。还有其他几个人,但是似乎我没有在routes.rb文件中做某件事,或者comments.html.erb中的link_to是错误的。我会更新以包含路线代码。 – bgadoci 2010-04-12 03:34:17

回答

12

meagar是在正确的道路上,但由于这是一个嵌套的路线,你需要做的:

<%= link_to 'Destroy', [@post, comment], ... %>

所以,要传递的评论和帖子,让铁轨找出基于路线在你的定义上。

+0

谢谢。似乎我尝试过所有的组合,但这个。完美工作。 – bgadoci 2010-04-12 03:45:09

1

_comments.html.erb中,更改您的link_to

<%= link_to 'Destroy', comment, ... %> 

IE,传递给它本身comment,而不是整个阵列@comments

+0

我得到这个错误,当我这样做:未定义的方法'comment_path'为# bgadoci 2010-04-12 03:28:33