简体   繁体   中英

Showing error messages for nested resources in Rails

I am creating my first app, simple blog, and I don't know how to show error messages for nested resource(comments) that doesn't pass validation.

this is create action for comments:

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

this is comment form:

  <%= 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 %>

I tried with:

  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

and:

  <% 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 %>

But I don't know whats wrong.

You can't render a partial from a controller. A better alternative is just to create a new view.

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

app/views/comments/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/comments/_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 %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM