Create models within model
I have two models: Report
and SinglePage
.
A user can upload a PDF-Report. Every Page of this report gets turned into an image and is saved into its own single_page-instance.
Currently, I am saving the report (in my controller), and if the save is successful, I create the single_pages for this report (also from within the controller).
I don't like this approach, since this kind of logic should be handled within the model itself. Another problem is, that the report gets created, no matter if the single_pages for the report can be created or not. Of course, I could catch in the controller, but I consider this a bad practice.
What I actually want to achieve is this:
- The user uploads a PDF-Report
- The report gets split and each si开发者_运维技巧ngle page is turned into an image
- Each image is saved into its own single_page-instance
- NOTE: The single_pages are all created within a single method, which returns false, if one or more pages can't be created.
- Only if all the single_pages get created, the report gets saved.
I tried to override the initialize-method within the Report-Model, but I am not getting this dependency to work. Either the report-model itself has an error, or it gets saved, no matter what's the deal with the single_pages.
Any help would be very much appreciated.
Thanks, Mandi
Have you tried any of the callbacks available, such as before_create
or before_save
, on Report
?
You can wrap all the saves up in a transaction.
Also, you didn't mention it, but I assume you have a parent-child relationship between Reports and SinglePages? If so, then if you build (not save) the pages and then save the report, rails will try to save the dependent children and will not save the parent if the children fail to save.
精彩评论