How should I validate data going into multiple tables that all depend on each other?
I have a debate site, where users can start a debate and with their debate submit "survey options" so people can choose an option when they reply to the debate.
The validation process goes like this, the debate model validates that the columns specific to the debate table are valid (topic and body). The options model validates that the options supplied with the debate are valid (text). The category model validates that the category that the user supplied for that debate actually exists.
I make sure everything exists before I add anything to the database. So when adding a debate, I would make sure the category exists. When adding a survey option to a debate, I want to make sure the debate exists.
The problem arises when creating a new debate with survey options at the same time. By making it so that the debate exists prior to adding a new option, I end up in a catch-22. The debate won't add (and therefore won't exist) unless everything validates, and the survey options won't validate unless the debate exists, because it needs a debate id to bind to.
Should I remove开发者_C百科 this logic from my survey options? What should I do?
Don't allow users to create the debate topic and the survey options with the same form submission.
You can maintain good UX by using AJAX to have users create the debate topic first and then allow the survey options to be created on the same page. The survey options form can either be grayed out or invisible until the debate topic is created.
The alternative of writing a workaround into your validation logic will make it harder to test and maintain your code.
精彩评论