Is it possible to save a file in a dependent model entity when the parent (base) entity has not yet been saved?
I would like the user to be able to add images to a story prior to the story actually being saved. So my model is like this:
Story (Base Entity) has_many :pictures
+ Picture (Depedent Entity) belongs_to :story
In the Story controller, I have a separate action called add_image. However, because the instance variable @story does not seem to be persisted across requests, I cannot access it in this action.
What I have thought of doing so far is to store the @story variable in the session on create, so I can retrieve it from there. Will this work? May it have any unintended side-effects for subsequent requests? (E.g. what if I have the previous story stored in the session and add a picture to the wrong story?).
Apparently it is possible to save dependent records together with the main on first create:
http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html
See the section “Unsaved objects and associations”. You must use collection.build to add the dependent records.
Now my problem is still how to reliably persist the parent across requests, though I am thinking this may be possible by storing it in the session with the ID generated by mongoid (the only problem being that it is not portable across ORMs, I think).
This answers part of my question. So I will not accept any answer just yet, and once I have found a proper solution, I will give an update.