好吧,我将尽力解释这一点。
我有一个TopicsController,它的内部有一个Show方法,该方法遍历主题模型并显示所有需要的信息,在它下面,我有一个帖子模型的表单。问题是。如果验证失败,则错误消息将拒绝显示。我已经尝试了一切,但我不知道该怎么办。我有一个应该工作的自定义错误部分。
控制器:
def create
@community_post.user_id = current_user.id
@community_post.community_topic_id = params[:community_topic_id]
if @community_post.save
redirect_to "/community_topics/#{@community_post.community_topic_id}", notice: 'Community post was successfully created.'
else
redirect_to "/community_topics/#{@community_post.community_topic_id}", notice: 'Community post was NOT successfully created.'
@community_post.community_topic_id = nil
end
end
看法:
<h1> Submit reply </h1>
<% @community_post = CommunityPost.new %>
<%= form_for(@community_post) do |f| %>
<%= render 'error_messages_posts' %>
<%= f.label :text %>
<%= f.text_area :text %>
<%= hidden_field_tag :community_topic_id, @community_topic.id %>
<br>
<%= f.submit "Submit reply" %>
<% end %>
部分的:
<% if @community_post.errors.any? %>
<div id="error_explanation">
<div class="alert alert-error">
The form contains <%= pluralize(@community_post.errors.count, "error") %>.
</div>
<ul>
<% @community_post.errors.full_messages.each do |msg| %>
<li>* <%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
当您将流重定向到时/community_topics/#{@community_post.community_topic_id}
,变量@community_post
中的错误值会丢失。
您可以再次渲染相同的表单,也可以在通知中传递错误消息(例如 redirect_to "/community_topics/#{@community_post.community_topic_id}", notice: "Community post was NOT successfully created. Errors : #{@community_post.errors.full_messages.join(', ')}")
谢谢。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句