2012-09-25 42 views
0

我有一個應用程序,其中包含評論的帖子。Rails編輯評論不顯示數據

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

更改新來

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| %>