Reputation: 175
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.
Upvotes: 1
Views: 1339
Reputation: 102250
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 %>
Upvotes: 3