Following the helpful tutorial in Railscasts #38 http://railscasts.com/episodes/38-multibutton-form I set up a “Preview” button for my “New”/”Create” controller actions.
But when I use the same method for “Edit”/”Update” there seems to be a problem.
I can’t seem to get my form to persist.
Here’s what my controller looks like:
def update
stylesheets << 'feature'
@feature = Feature.find(params[:id])
case params[:submit]
when "Preview"
render :action => "edit"
return
when "Update"
respond_to do |format|
if @feature.update_attributes(params[:feature])
flash[:notice] = 'Feature was successfully updated.'
format.html { redirect_to(features_path) }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @feature.errors, :status => :unprocessable_entity }
end
end
return
end
end
When I hit the preview button, I am returned to an editing screen as expected, but my edits don’t persist. Any tips? Curious, as this works fine for previewing New objects.
What’s happening here is that you’re not actually applying the changes the user made to the in-memory model before rendering your view, so the changes get lost.
Try changing your ‘Preview’ case like this:
One thing I would say is that I’d also consider splitting that method up a bit to make it easier to read and test. Something like this:
This helps you keep your tests simple and focussed on one method at a time, and should make the code easier to maintain.