In a database where there is a many to many relationship (say 3 tables like this for example)
Book | Author | BookAuthor
_____ | ______ | __________
BookId | AuthorId | BookId
Title | Name | AuthorId
... | ... |
I want a form to create a new book. In that form, the users would enter the information about the book (Title, etc.) and they would select the authors for the book, all through the same form.
In a situation like that, when do you do the insert in the Book table? Do you do it when :
you access the form, so that you get the BookId and that you can insert in the BookAuthor table as the user adds the authors?
do it only when the user leaves the form (you insert in Book and then in BookAuthor)?
With 1, you could end up with a bunch of unwanted records, as a record is created even when the users leave the page or hit cancel.
With 2, you don't have the BookId, so you can't start inserting in the BookAuthor table until the whole form is filled (you can't really use AJAX then).
This seems like it would be a fairly common scenario, so I imagine that there is a correct way of doing this?
EDIT : The authors could be added like the tags are added to a question on Stack Overflow (auto-complete box) like it was suggested in an answer. You add a tag, but it can't be inserted right away because the question doesn't exist in the database yet. So when you submit your question, I'm guessing that the content of the auto-complete box is parsed and that both (tags and question) are inserted at the same time. I don't know how it's done on SO (parsing or something else) but that's basically what i'm trying to find out.