拒绝显示[RoR]的错误消息

时间:2013-12-20 09:34:21

标签: ruby-on-rails ruby

好的,我会尽力解释这个。

我有一个ThemeController,里面有一个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 %>

3 个答案:

答案 0 :(得分:2)

您正在使用

的表单创建一个新实例
<% @community_post  = CommunityPost.new %>

现在此对象没有任何错误消息,这就是为什么您无法看到任何错误消息。你也将它重定向到其他动作,行动不知道你的对象。消息,所以你做的每件事都错了

答案 1 :(得分:0)

当您将流重定向到/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(', ')}")

感谢。

答案 2 :(得分:0)

删除第@comminity_post = CommunityPost.new()行,因为它会创建一个没有任何错误的新帖子。

另外,通过创建操作呈现表单。

render :new

从其他控制器渲染视图

render :template => "controller/action"