I have 2 controllers: DocumentsController and DashboardController
After the user login successful, he is redirected to dashboard_path, which has a form to create a ‘fast document’ like this
<%= form_for @document, :html => {:class => 'well'} do |f| %>
<% if @document.errors.any? %>
<div id="alert alert-block">
<div class="alert alert-error">
<h2>Couldn't create your doc. :(</h2>
<ul>
<% @document.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
</div>
<% end %>
<label>A lot of fields</label>
<%= f.text_field :fields %>
<div class="form-actions">
<%= f.submit 'Create document', :class => 'btn btn-large' %>
</div>
<% end %>
but when an exception happen (like the user forgot to fill a field), I would like to show these exceptions, not just an alert saying ‘Error’…actually, I didn’t found a way to do this
here’s my DashboarController
class DashboardController < ApplicationController
before_filter :authenticate
def index
@document = Document.new
end
end
and my DocumentsController
class DocumentsController < ApplicationController
respond_to :json, :html
def show
end
def create
@document = Document.new(params[:document])
@document.user = current_user
if @document.save
redirect_to dashboard_path, notice: 'Created!'
else
flash[:error] = 'Error!'
redirect_to dashboard_path
end
end
end
any help is appreciated 🙂
You are correctly redirecting on success; on failure, though, should not redirect; you need to render the template where the form was filled.
You’ll have to make sure that any variables needed by the index template are available in the create action of the documents_controller (you’re just rendering the index template; you’re not running the code from the dashboard controller’s index action). Here’s a excerpt from the relevant Rails Guide to clarify:
More at http://guides.rubyonrails.org/layouts_and_rendering.html#using-render