Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Best way to return recently created object in ActiveRecord?

I’m creating an object that when called it will create an database record and I want this function to return the newly created object. This is what I got:

data = {foo: 'foo', bar: 'bar'}

Dummy.new(data).save! # true
Dummy.last # newest record in the database

I’m concerned about what this would mean when there are more than one sessions on the same database. Is there a sure-fire way of getting the record I just created?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Just assign the instance you created to a variable:

data = {foo: 'foo', bar: 'bar'}

dummy = Dummy.new(data)
dummy.save!
dummy # the record you just created

Or use create! instead of new and save! like this:

data = {foo: 'foo', bar: 'bar'}

Dummy.create!(data) # returns the created instance or raises an error if not successful
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading