Rails rails 入门中的 comment 如何编辑修改

rubybird · 2013年02月05日 · 最后由 rubybird 回复于 2013年02月18日 · 3172 次阅读

初学 Rails,根据入门介绍,建立了入门的 blog。入门里介绍了如何创建一个 comment。可是创建后,如何修改和删除呢?

我尝试在 controllers/comments_controller.rb 中添加了一个方法

def edit
  @post = Post.find(params[:post_id])
  @comment = @post.comments.find(params[:id])

end

然后在 comments/_form.html.haml 中添加了

= form_for([@post]) do |f|
  - f.fields_for :comments do |comment_form|
    .field
      = comment_form.label :commenter
      %br/
      = comment_form.text_field :commenter
    .field
      = comment_form.label :body
      %br/
      = comment_form.text_area :body
    .actions
      = comment_form.submit

在 posts/show.html.haml 中添加一个编辑连接

= link_to 'Edit', edit_post_comment_path(comment)

创建一个 post 和一个 comment 后,点击上面的 Edit 进入,发现comment 的提交表格中的各个域都是空的,更像是创建一个新的 comment,而不是编辑

各位,有什么办法进行编辑 comment 不?同时,又怎么加删除 comment 的功能?

刚刚看到了删除的功能,但是在 post 下编辑 conmment,还是没有发现

2 楼 已删除

从你目前给的信息,有个疑问 f.fields_for :comments 你这么写是一对多关系吧?那么@post下面你到底要显示哪一条 comment?

增加删除的方法 @comment = Comment.find(params[:id]) @comment.destroy 路径看 rake routes

参考这个:http://stackoverflow.com/questions/9480741/what-variable-should-i-place-in-this-form-to-edit-a-comment-rails

把 app/views/comments/_form.html.haml 改为

= form_for([@post, @comments]) do |f| 
  .field
    = f.label :commenter
    %br/
    = f.text_field :commenter
  .field
    = f.label :body 
    %br/
    = f.text_area :body
  .actions
    = f.submit 

然后在 app/controllers/posts_controller.rb 的 show 中添加

@comments = @post.comments.build

在 app/controllers/comments_controller.rb 的 edit 中修改如下

def edit
  @post = Post.find(params[:post_id])
  @comments = @post.comments.find(params[:id])
end

现在可以编辑了,感谢大家

需要 登录 后方可回复, 如果你还没有账号请 注册新账号