Search code examples
mysqlruby-on-rails-3lastinsertid

Rails 3 - how to find last inserted ID from mysql table


in my controller I have following sequence of commands:

SAVE DATA INTO FIRST TABLE

_get ID of inserted item into table from first step_

SAVE DATA INTO SECOND TABLE WITH ID FROM FIRST COMMAND

if FIRST.save && SECOND.save
 do something

And I am wondering, how to get id of item, which is immediately inserted into database... I tried to googling, but I can't find this information...

Thanks in advance for your hints


Solution

  • # SAVE DATA INTO FIRST TABLE
    first_instance = FirstModel.new( :foo => :bar )
    first_save = first_instance.save
    
    # _get ID of inserted item into table from first step_
    first_instance_id = first_instance.id
    
    # SAVE DATA INTO SECOND TABLE WITH ID FROM FIRST COMMAND
    second_save = SecondModel.new( :first_model_id => first_instance_id ).save
    
    if first_save && second_save
      # do something
    end