In my app, I have created a form to create new posts (Post is a model). I have a controller with the name posts. The form is located in the admins controller. The form use the form_for(@post). It post to the post controller. In this method, the post gets created successfully. But the problem is with failed submissions. In the form, I have added the code to show the errors
<% if @post.errors.any? %>
<div id="error_explanation">
<div class="alert alert-error">
The form contains <%= pluralize(@post.errors.count, "error") %>
</div>
<ul>
<% @post.errors.full_messages.each do |msg| %>
<li> <%= msg %> </li>
<% end %>
</ul>
</div>
<% end %>
But in the post controller, if there’s a failed submission, I have set it to redirect_to the newpost page in the admins controller. When redirecting, I will loose the error messages.
So, I added
render 'dasharea/newpost'
localhost:3000/dasharea/newpost is the URL of the page that have the form. With this code, it say
Missing template dasharea/newpost with {:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder, :coffee]}.
But Im already in that page? Then I tried to add the controller and the action like this (note: im editing the create action of posts controller. I need to render the newpost action in admins controller) :
render 'admins/newpost'
Then, it will direct me to the posts :
http://localhost:3000/posts
But now, the form is there and I can see the errors. But I need to render the oroginal page which I have the form (dasharea/newpost)! How can I do this? What have I done wrong?
My solution: AJAX form. No more issues. Update the form on the spot with javascript. You can even redirect using
window.location.href = '/your-url'if needed.If you need to handle html requests, you could always point your form to the url of your choice:
Handle the create_post action on this controller and make sure your routes are set properly. The bad side of it is that you’ll be handling posts creation in a different controller than your PostsController.