ruby on rails - AbstractController::DoubleRenderError Error and using redirect_to -
i have update method using save , delete methods having own render calls. below code:
update method:
def update_book self.delete_book params[:name] = params[:newname] self.save_book end
delete method:
def delete_book # rescue bookdoesnotexist => exception render status: 404 return end head 200 end
save method:
def save_book # rescue bookdoesnotexist => exception render status: 404 return end rescue bookalreadyexist => exception render status: 409 return end head 200 end
when run input system throws "abstractcontroller::doublerendererror
" error along message "render and/or redirect called multiple times in action. please note may call render or redirect, , @ once per action. note neither redirect nor render terminate execution of action, if want exit action after redirecting, need "redirect_to(...) , return
"
i understand because throwing exception in both delete , save method input passing. how handle scenario?
doing research learnt need use redirect. understand when delete method throws exception/renders should return , should not call save method.
here tried redirect_to:
update method:
def update_book redirect_to action: self.delete_book , return if status=404 end params[:name] = params[:newname] self.save_book end
am doing right or there other best way handle redirect?
when delete_book
or save_book
methods receive exception render , return, correct.
but return
give execution caller method, update_book
. caller method have no idea of exception occurred , therefore job , render has render.
to fix, delete_book
or save_book
methods need return success status caller, this:
def delete_book # ... rescue bookdoesnotexist => exception render status: 404 return false end head 200 true end
then caller method shall check status:
def update_book return unless self.delete_book params[:name] = params[:newname] return unless self.save_book end
an alternative keep code clear heavy exception testing use controller'srescue_from
.
in applicationcontroller
:
class applicationcontroller < actioncontroller::base rescue_from bookdoesnotexist, with: :redirect_book_not_existing private def redirect_book_not_existing render status: 404 end end
from on, time controllers receive bookdoesnotexist
exception, execution stop , render status: 404
line executed. off course must not rescue
exceptions in other method, this:
def delete_book # head 200 end
your code cleaner
Comments
Post a Comment