1

我正在基本的博客引擎上工作,我已對註釋應用驗證,但是當我提交時不顯示錯誤,而是顯示默認情況下使用rails的ActiveRecord :: RecordInvalid 。評論驗證錯誤未在帖子視圖中顯示

我的意見控制器

def create 
@post = Post.find(params[:post_id]) 
@comment = @post.comments.create!(params[:comment]) 
redirect_to @post 
end 

我的職位/顯示示意圖如下該意見徵求

<%= form_for [@post, Comment.new] do |f| %> 
<p class="comment-notes">Your email address will not be published. Required fields are marked <span class="required">*</span></p> 
<p> 
<b><%= f.label :name, "Name * " %></b><%= f.text_field :name %><br /></p> 
<p> 
<b><%= f.label :body, "Comment" %></b><%= f.text_area :comment, :cols => 60, :rows => 5 %> 
</p> 
<p> 
    <%= f.submit "Post Comment" %> 
</p> 

任何人可以幫助我,以顯示在同一崗位驗證錯誤/顯示工作正常視圖?

在此先感謝

回答

4

更換

@comment = @post.comments.create!(params[:comment]) 
redirect_to @post 

@comment = @post.comments.create(params[:comment]) 
if @comment.errors.any? 
    render "posts/show" 
else 
    redirect_to @post 
end 

不像創建,創造!會引發錯誤,如果驗證失敗,在帖子中

/顯示

<%= form_for [@post, Comment.new] do |f| %> 
    <% if @comment && @comment.errors.any? %> 
    <% @comment.errors.full_messages.each do |msg| %> 
    <li><%= msg %></li> 
    <% end %> 
    <% end %> 
    ... 
+0

確定它通過創建方法停止引發錯誤,但它仍然不顯示驗證錯誤 – shail85

+0

更新了答案 – shweta

+0

謝謝。這解決了這個問題。 – shail85

0

試試這個:

def create 
    @post = Post.find(params[:post_id]) 
    @comment = @post.comments.new(params[:comment]) 
    if @post.save 
    redirect_to @post 
    else 
    flash[:error] = "Correct errors" 
    end 
end 

在Post模型:

accepts_nested_attributes_for :comments 

or 

如果你不這樣做想要作爲嵌套模型:

def create 
    @post = Post.find(params[:post_id]) 
    @comment = @post.comments.new(params[:comment]) 
    if @comment.save 
    redirect_to @post 
    else 
    flash[:error] = "Correct errors" 
    end 
end