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條件並在錯誤上填充一些魔術變量? 還是我犯了一些完全不同的錯誤?