Render the action that initiated update
I have a SettingsController with actions account and profile, and also an update that loo开发者_如何学Pythonks like:
def update
@player = current_user
if @player.update_attributes(params[:player])
flash[:success] = "Profile updated."
redirect_to :back
else
@title = "Edit"
render
end
end
Now the profile and account actions each have a corresponding view, with a form to edit some records of the Player model.
When you try to save one of those forms, and it fails, ie. it didn't pass validation, it should render the action that initialized the update again, so it can display appropiate error messages.
But the problem is, how do I know which of both requested the update, and render the right one? Basically some sort of equivalent of redirect_to :back is what I'm looking for here.
This is ugly but works :)
render Rails.application.routes.recognize_path(request.referer)[:action]
Usually you can fix this by applying a pattern:
def edit
@title = "Edit"
# ...
end
def update
# Update using the exception-generating variant
@player.update_attributes!(params[:player])
# ... More actions if successful
rescue ActiveRecord::RecordInvalid
self.edit
render(:action => 'edit')
end
This is often simplified by having a before_filter
that handles the loading of the model instance for you.
Since this can be used a lot, sometimes you can wrap that into a delegation method:
def fallback_render(action)
send(action)
render(:action => action)
end
精彩评论