I have the following:
routes.rb:
resources :posts do
resources :replies
end
replies_controller.rb:
class RepliesController < ApplicationController
def create
@post = Post.find(params[:post_id])
@reply = @post.replies.build(params[:reply])
@reply.user_id = current_user.id
if @reply.save
flash[:success] = "reply created!"
redirect_to post_path(@post)
else
redirect_to post_path(@post)
end
end
replies/_form.html.erb:
<%= form_for([@post, @post.replies.build]) do |f| %>
<%= render 'shared/error_messages', object: f.object, target: @reply %>
<div class="field">
<%= f.text_area :content, placeholder: "Enter reply content" %>
</div>
<%= f.submit "Reply", class: "btn btn-large btn-primary" %>
<% end %>
posts/show.html.erb:
<div class="span8">
<%= render 'replies/form' %>
</div>
shared/error_messages.html.erb:
<% if object.errors.any? %>
<div id="error_explanation">
<div class="alert alert-error">
The form contains <%= pluralize(object.errors.count, "error") %>.
</div>
<ul>
<% object.errors.full_messages.each do |msg| %>
<li>* <%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
I’m not sure why the errors messages for the replies are not displaying since I’m using target: @reply (:content and :user_id are required).
Any suggestions to fix this?
In create method’s else section you have to render the post_path(@post) not redirect the post_path(@post)
try this in else part of create section
So that your current @reply object will persist for your error messages.
redirect_to post_path(@post) will redefine @reply object in show action (I assume you have defined @reply object there).
In posts/show action, build your reply object there and assign it to @reply instance object.
Now in replies/_form.html.erb:
change @post.replies.build to @reply
i.e
to
Also assign @reply to object variable while rendering ‘shared/error_messages’ partial,
Also make partial for error_messages in shared folder (shared/_error_messages). In this partial paste your code which is in shared/error_messages