【问题标题】:Showing error messages for nested resources in Rails在 Rails 中显示嵌套资源的错误消息
【发布时间】:2016-10-06 22:37:06
【问题描述】:

我正在创建我的第一个应用程序,即简单的博客,但我不知道如何显示未通过验证的嵌套资源 (cmets) 的错误消息。

这是 cmets 的创建操作:

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

这是评论表单:

  <%= form_for([@post, @post.comments.build]) do |f| %>
    <p>
      <%= f.label :commenter %><br />
      <%= f.text_field :commenter %>
    </p>

    <p>
      <%= f.label :text %><br />
      <%= f.text_area :text %>
    </p>

    <p>
      <%= f.submit %>
    </p>
  <% end %>

我试过了:

  def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.build(comment_params)

    if @comment.save
      redirect_to post_path(@post)
    else
      render '/comments/_form'
    end
  end

和:

  <% if @comment.errors.any? %>
    <div id="error_explanation">
      <h2>
        <%= pluralize(@comment.errors.count, "error") %> prohibited
        this comment from being saved:
      </h2>
      <ul>
        <% @comment.errors.full_messages.each do |msg| %>
          <li><%= msg %></li>
        <% end %>
      </ul>
    </div>
  <% end %>

但我不知道怎么了。

【问题讨论】:

  • 嗨,欢迎来到 Stack Overflow。您能否扩展“我不知道出了什么问题”。 - 解释你观察到的和你期望看到的?
  • hmmm 实际上我认为您的问题是这一行:render '/comments/_form' - 您应该改为重新渲染“新”操作,例如 render :action =&gt; :new... 而不仅仅是单独渲染表单,但整个新页面。

标签: ruby-on-rails ruby-on-rails-4 ruby-on-rails-5


【解决方案1】:

您不能从控制器渲染部分内容。更好的选择是创建一个new 视图。

class CommentsController
  def create
    if @comment.save
      redirect_to post_path(@post), success: 'comment created'
    else
      render :new
    end
  end
end

app/views/cmets/new.html.erb:

<% if @comment.errors.any? %>
  <div id="error_explanation">
    <h2>
      <%= pluralize(@comment.errors.count, "error") %> prohibited
      this comment from being saved:
    </h2>
    <ul>
      <% @comment.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
    </ul>
  </div>
<% end %>
<%= render partial: 'form', comment: @comment %>

app/views/cmets/_form.html.erb:

<%= form_for([@post, local_assigns[:comment] || @post.comments.build]) do |f| %>
    <p>
        <%= f.label :commenter %><br />
        <%= f.text_field :commenter %>
    </p>

    <p>
        <%= f.label :text %><br />
        <%= f.text_area :text %>
    </p>

    <p>
        <%= f.submit %>
    </p>
<% end %>

【讨论】:

  • 请注意,例如,如果用户从 post show 视图创建 cmets,您实际上并不需要在控制器中执行新操作。
  • 谢谢 Max,就是这样 :) 不知道不能从控制器渲染部分
猜你喜欢
  • 2014-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多