So, The situation is like this:
I have one table called invoice, and it has a column called invoice #, I have to generate a complex invoice number every time before it was saved to the database.
And besides, I have another table called invoice_item, which will store a mess of items. each item also has a column called invoice # to declare that which invoice the item is belonged.
There is no limit that how many items will be in one invoice.
Now, I have 2 strategies to achieve this:
-
I have a function called generateCode() to return a random invoice #. I will put it in application_controller.rb, And every time, when we try to insert a new invoice, The method “create” in invoice_controller will generate an new invoice #, and pass the value to all the invoice_items which is belonged to the invoice.
-
I will use the ActiveRecord callback function: after_initialize, so, when we try to new an invoice instance, the invoice # will be also created, and it will be easy to pass the value to the item list.
It seems that the 2nd way has more logic, but does it have some chance to lead to a performance problem? and in most E-commercial website, the user most likely get their invoice # after they submit the shopping list. so I wanna know that what is the typical way to do this kind of questions, and more important, why?
Thanks
after_initializeoperates every time you instantiate an ActiveRecord object, meaning that when you retrieveinvoice_itemsfrom the database, they will get new invoice numbers (not what you want).The callback you should use is
before_create, which will fire on new objects before they are saved to the database.