Reputation: 696
I have 2 related models and I need to validate and create them together.
Application
class Application < ActiveRecord::Base
has_many :application_sessions, inverse_of: :application
ApplicationsSession
class ApplicationSession < ActiveRecord::Base
belongs_to :application, inverse_of: :application_sessions
If it was possible I'd like to create an Application
through an ApplicationSession
butapplication_session.build_application
won't work because it will never be a valid record.
application_session.create_application
wont work either because even if ApplicationSession
is not a valid record, it will create an Application
.
For the first one; it validates Application
and ApplicationSession
. This logic might work fine if I only skip application_id
validation for ApplicationSession
if when Application
is a valid record. Still I prefer to use a more elegant solution if there is any.
For the second one; I can delete the Application
afterwards if ApplicationSession
is not a valid record but I didn't quite like this solution.
What is best approach to create/not to create those dependent records together with Rails?
Clarification:
Simply, I want the parent and child to be created together while there is no parent exists and a valid child about to save (valid expect it does not have any parent). If child is not a valid record, nothing should be created.
Upvotes: 0
Views: 106
Reputation: 71
I think using new and build would work.
application = Application.new({attr1: val1, attr2: val2 ..})
application.application_sessions.build({attr1: val1, attr2: val2 ..})
application.save
In this way, if application is invalid, application and its new application_session would not be saved. The same goes if the application_session is invalid.
In terminal where you fired-up your rails console
command, you would see something like:
(0.1ms) begin transaction
(0.1ms) rollback transaction
If application and its new application_session are both valid, both would be saved :)
Upvotes: 1
Reputation: 2380
From a data modelling point of view I'm not sure what you're trying to do.
I think you have a parent/child relationship where the parent is optional?
If you create a parent and then delete it you will have dangling keys in the child that point to nothing, be far better to just have nulls in there.
Is there any reason you can't just call new or create with a null parent id? Is the parent key mandatory? If so turn off the mandatory requirement and it should work. Build only works from parent to child, not the other way round when all the keys are null. I think you have to call save on the parent and the children are saved once the parent ID is known.
If the parent must exist for your app to work create a dummy one and have all the children you don't want to have a specific parent belonging to it, then you can easily find them again. Without knowing the flow of your app I'm not sure what else I could advise.
Upvotes: 0