Search code examples
ruby-on-railsrubyactiverecordrails-activerecord

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?


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