Say we have the models Patient and PatientRawData (with a belongs_to association to Patient).
Is it possible to create new records (without saving them in database), associate them, and finally save them in the database?
Something like this:
patient = Patient.new(:name => 'John', :age => 34)
rawtext = PatientRawText.new(:rawtext => 'My name is..')
patient.rawtext = rawtext
patient.save!
The reason I want to do this, is that in my real case scenario there might more complex models/associations and I would prefer to not have partial things in the database in case of an exception.
For this reason I prefer to build whatever complex thing I want, and as a final step to store the whole thing in the database.
Rails have out of the box support for this type of issues using nested attributes. http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html
class Patient < ActiveRecord::Base
has_one :patient_raw_text
accepts_nested_attributes_for :patient_raw_text
end
params = { patient: { name: 'Jack', patient_raw_text_attributes: { rawtext: '...' } }}
member = Patient .create(params[:patient])
You can use transaction to prevent a bunch of records being created. It will roll back all ActiveRecord saves if an exception occurs anywhere in the block.
ActiveRecord::Base.transaction do
patient = Patient.new(:name => 'John', :age => 34)
rawtext = PatientRawText.create!(:rawtext => 'My name is..')
patient.rawtext = rawtext
patient.save! # <- if this fails
raise "I don't want to be here" # <- or if you manually raise an exeption
end
If an exception is raised, even after the PatientRawText object was successfully created (say if patient.save! fails) then the PatientRawText creation will be rolled back.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With