I’m getting a double render error that I cannot get rid of in the update method of my model.
Here’s the code for the controller
class Admin::CmsHappeningNowFeatureController < ApplicationController
def index
# Various model data retrieval...
render 'admin/cms/hn_features/index', layout: 'admin_cms'
end
# Works fine
def edit
@feature = CmsHappeningNowFeature.find_by_id(params[:id])
render 'admin/cms/hn_features/feature', layout: 'admin_cms'
end
# Throws a AbstractController::DoubleRenderError upon submission
def update
@feature = CmsHappeningNowFeature.find_by_id(params[:id])
@feature.attributes = params[:cms_happening_now_feature]
if @feature.save
redirect_to(:action => index, :notice => "Successfully updated feature.") and return
end
render 'admin/cms/hn_features/feature', layout: 'admin_cms'
end
# ... rest of the class
end
When redirecting to another controller, the issue disappears. It seems that redirecting to the same controller makes rails execute the method without actually sending a redirect. By looking at the log, when submitting the update form, update gets called, then index gets called, render from index is executed and then the redirect is issued and fails.
What am I missing? What’s the workaround?
Okay, the real cause is that in
you call the
indexmethod which will then render first. Theredirect_tocall will then get the result of that function back (which will be whatever therendercall inindexreturns). and renders the second timeWhat you really want to write is this:
where you set
:actionto a symbol, i.e. index which represents the action but does not directly call it.