Hey guys I have a simple create method with some validations and whenever the create method fails due to validation errors it re-renders the开发者_JAVA技巧 'new' action.
The problem is in my new action/view I have a local variable that is established in the action and passed to a partial to render some related information to what the user is creating.
Now when my create action fails and I try to re-render the 'new' action I'm getting the always awesome
undefined method `cover' for nil:NilClass
error.
What is the best way to handle re-establishing my action's local variables on a render instead of redirecting to the action again and the user losing the data they input?
For some clarification. Here is some sample code:
#controller.rb
def new
@summary = User.find(params[:user_id])
@page = Page.new
end
def create
@page = Page.new(params[:page])
if @page.save
redirect_to @page
else
render :action => 'new'
end
end
in my new.html.erb file i have something like this
<%= @summary.cover %>
#page form etc...
When you create the object and attempt to save it, the object still holds the values and the validation errors, so pass it on into the render. Usually it is named the same in your create method as it is in your new method, so the template just works.
if @my_object.save
flash[:notice] = "Successfully created."
redirect_to ....
else
render :action => 'new' #assuming new.html.erb uses @my_object
end
精彩评论