0

我有一篇文章has_many :comments和一個評論belongs_to :post。 On/posts /:id(後顯示方法)我呈現一個表單,用戶可以在其中留言。預先填寫窗體從關聯的對象錯誤在Rails

它的所有作品,驗證,測試和發佈都很好。唯一缺少的是如何在驗證錯誤上重新呈現POST數據。

這種情況的(簡化的)代碼是:

#app/controllers/posts_controller.rb 
class PostsController < ApplicationController 
    def index 
    @posts = Post.all_published(params[:page]) 
    @title = "Blog" 
    end 

    def show 
    @post = Post.where({:published => true}).find(params[:id]) 
    @comment = Comment.new(:post => @post) 
    @title = @post.title 
    end 
end 

#app/controllers/comments_controller.rb 
class CommentsController < ApplicationController 
    def create 
    @comment = Comment.new(params[:comment]) 
puts @comment 

    if @comment.save 
     flash[:notice] = 'Comment was successfully created.' 
     redirect_to(@comment.post) 
    else 
     flash[:notice] = "Error creating comment: #{@comment.errors}" 
     redirect_to(@comment.post) 
    end 
    end 
end 

#app/views/posts/show.haml 
.html renders Post contents. 

- form_for @comment do |f| 
    = f.hidden_field :post_id 
    = f.text_area :body 
    = f.text_field :name 
    .some more fields. 

我期望的解決方案是要麼在comments_controller.rb一些神奇聲明,部分

else 
     flash[:notice] = "Error creating comment: #{@comment.errors}" 
     redirect_to(@comment.post) 
    end 

還是在PostsController.show其中我準備@comment。我是否應該設置@comment條件並在錯誤上填充一些魔術變量? 還是我犯了一些完全不同的錯誤?

回答

1

如果您重定向,該數據通常是失去了,這就是爲什麼在大多數情況下,在創建創建動作,你會注意到,在情況下,渲染沒有redirect_to的

因此,你可以只是嘗試,

 
flash[:notice] = ""Error creating comment: #{@comment.errors}" 
render :template => "posts/show" 
@post = @comment.post 
# you may need to pre-populate the instance variables used inside PostsController#show 
相關問題