Rails Multiple forms in one view rendering errors issue
I have built a dashboard of sorts with multiple forms from different models in the same view. My goal is to have all of the error messages from each form render on the dashboard. The dashboard is part of the PagesController and the forms belong to other controllers.
All of the forms currently work great. However, when errors occur they render in other views not the dashboard. When I attempt to "render" the errors on the dashboard page I get errors that the other form's models are missing.
Example of "render" that renders outside of the dashboard view.
class NotesController < ApplicationController
def create
@note = Note.new(params[:note])
if @note.save
flash[:notice] = "Note Created!"
redirect_to dashboard_path
else
flash[:alert] = "Note failed"
render :action => "new"
end
end
end
The example I would like to work, which renders the errors inside the dashboard view.
class NotesController < ApplicationController
def create
@note = Note.new开发者_JS百科(params[:note])
if @note.save
flash[:notice] = "Note Created!"
redirect_to dashboard_path
else
flash[:alert] = "Note failed"
render 'pages/home'
end
end
end
To reiterate, I am trying to make it so all errors will show up on the dashboard page with out breaking the site. Let me know if you would like more information.
You can accomplished this by just setting errors to an instance variable that all the forms use:
class NotesController < ApplicationController
def create
@note = Note.new(params[:note])
if @note.save
flash[:notice] = "Note Created!"
redirect_to dashboard_path
else
@errors = @note.errors
load_home
render 'pages/home'
end
end
private
def load_home
@instances = Model.all
@instance_1 = Model.find(1)
end
end
All your controllers would set @errors = @model.errors then in your view you just have something like this instead of relying on f.error_messages or whatever you have in your form: (in haml)
- unless @errors.nil?
#errorExplanation
%h2 Please correct these errors
%ul
- for e in @errors
%li= e[1]
精彩评论