When to use render vs redirect_to when handling error validations

后端 未结 2 1667
猫巷女王i
猫巷女王i 2021-01-16 06:25

I have a fairly complex view that has multiple forms, lots of validations on those forms, paginations, and other features. When validations fail, I like to use render becau

2条回答
  •  时光说笑
    2021-01-16 07:05

    You should grasp things in their perspective.

    Why is render used instead of redirect:

    • when you use render, you pass the instantiated object

    • this object, newly created or updated, received some params

    • when attempting to save the object, validation was triggered and, if unsuccessful, added errors to the current instance

    • so your object in memory contains validation errors.

    But when you use redirect, you restart with a fresh stack which doesn't know anything about the former object in memory, there could not be any magic:

    • either the object is saved and you can get the persisted data from database

    • or if it's not saved, you can have some information you previously stored in session


    To answer your question a bit closer: before you use render, you have to instantiate all objects needed by the page.

    It's just logic the view fails if the expected instance variables are missing.

提交回复
热议问题