我正在研究基本的博客引擎,我已经对评论应用了验证,但是当我做提交时它没有显示错误,而是显示默认的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>
任何人都可以帮我在相同的帖子/节目视图中显示验证错误吗?
提前致谢
答案 0 :(得分: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
与create不同, create!会在验证失败时引发错误
帖子/节目
<%= form_for [@post, Comment.new] do |f| %>
<% if @comment && @comment.errors.any? %>
<% @comment.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
<% end %>
...
答案 1 :(得分: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