When to use render vs redirect_to when handling error validations

后端 未结 2 1668
猫巷女王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 06:59

    First, these are not compiler error - its run-time errors.
    Second, you should either check your data in the controller to make sure its being served properly for rendering OR do some conditional blocks in the view in order to cope with this different data structures.

    Lastly, redirect_to is just a technique of moving the user around, it could be used here but you still need to handle those errors, even in the redirected-to page...

    HTH

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题