views:

86

answers:

1

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 '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...
+3  A: 

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
DGM
the object in question is actually a different object than what is being created.
Jimmy
this lead me to the correct answer, I just initialized the object in my create method as well and it transfered over nicely, thanks!
Jimmy