我有一个包含评论帖子的应用。
class Comment < ActiveRecord::Base
belongs_to :post
end
当我尝试编辑现有评论时,表单为空白。
comments_form.html.erb:
<%= form_for([@post, @post.comments.build]) do |post_comment_form| %>
<div class="field">
<%= post_comment_form.label :commenter %><br />
<%= post_comment_form.text_field :commenter %>
</div>
<div class="field">
<%= post_comment_form.label :body %><br />
<%= post_comment_form.text_area :body %>
</div>
<div class="actions">
<%= post_comment_form.submit %>
</div>
<% end %>
comments_controller.rb:
def edit
@post = Post.find(params[:post_id])
@comment = @post.comments.find(params[:id])
end
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(params[:comment])
redirect_to post_path(@post)
end
def update
#@post = Post.find(params[:post_id])
#@comment = @post.comments.find(params[:id])
respond_to do |format|
#if @post.comments.update_attributes(params[:comment])
if @comment.update_attributes(params[:comment])
format.html { redirect_to @comment, notice: 'Comment was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
如何在编辑评论时确保数据以表格形式显示?
答案 0 :(得分:0)
将您的新操作更改为
def new
@post = Post.new
@comment = @post.comments.build
end
并且您的编辑操作正常
def edit
@post = Post.find(params[:post_id])
@comment = @post.comments.find(params[:id])
end
表单构建器应该像
<%= form_for([@post, @comment]) do |post_comment_form| %>