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