我无法在rails上更新我的评论。 我想更新一篇帖子的评论。 我可以生成表单并将数据检索到输入。但是当我点击提交时,显示错误。
帖子更新效果很好。 但评论更新不。
Ruby -v: ruby 2.0.0p384 (2014-01-12) [x86_64-linux-gnu]
Rails -v: Rails 4.2.5.1
我的路线
/posts/:post_id/comments(.:format) comments#index
/posts/:post_id/comments(.:format) comments#create
/posts/:post_id/comments/new(.:format) comments#new
/posts/:post_id/comments/:id/edit(.:format) comments#edit
/posts/:post_id/comments/:id(.:format) comments#show
/posts/:post_id/comments/:id(.:format) comments#update
/posts/:post_id/comments/:id(.:format) comments#update
/posts/:post_id/comments/:id(.:format) comments#destroy
/posts(.:format) posts#index
/posts(.:format) posts#create
/posts/new(.:format) posts#new
/posts/:id/edit(.:format) posts#edit
/posts/:id(.:format) posts#show
/posts/:id(.:format) posts#update
/posts/:id(.:format) posts#update
/posts/:id(.:format) posts#destroy
/ posts#index
comments_controller.rb
class CommentsController < ApplicationController
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(params[:comment].permit(:name, :body))
redirect_to post_path(@post)
end
def edit
@post = Post.find(params[:post_id])
@comment = @post.comments.find(params[:id])
end
def update
@post = Post.find(params[:post_id])
@comment = Comment.find(params[:id])
if @comment.update(params['post'].permit(:name, :body) )
redirect_to @post
else
render 'edit'
end
end
def destroy
@post = Post.find(params[:post_id])
@comment = @post.comments.find(params[:id])
@comment.destroy
redirect_to post_path(@post)
end
end
edit.html.erb
<%= form_for @comment, :url => { :action => "update" } do |f| %>
<div class="form-group">
<%= f.label :name %><br>
<%= f.text_field :name, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :body %><br>
<%= f.text_area :body, class: "form-control" %>
</div>
<div class="form-group">
<%= f.submit %>
</div>
<% end %>
型号:comment.rb
class Comment < ActiveRecord::Base
belongs_to :post
end
错误
undefined method `permit' for nil:NilClass
Extracted source (around line #18):
16 @post = Post.find(params[:post_id])
17 @comment = Comment.find(params[:id])
18 if @comment.update(params['post'].permit(:name, :body) )
19 redirect_to @post
20 else
21 render 'edit'
谢谢大家!
答案 0 :(得分:1)
您可能希望在params[:comment]
def update
@post = Post.find(params[:post_id])
@comment = Comment.find(params[:id])
if @comment.update(params['comment'].permit(:name, :body) )
redirect_to @post
else
render 'edit'
end
end
很少有其他事情:
update_attributes
上致电@comment
,而不是更新@post
找到评论,而不是直接加载 @comment = @post.comments.find(params[:id])