1

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

user1946705
  • 2,746
  • 13
  • 39
  • 56

3 Answers3

4
# 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
Mori
  • 25,288
  • 10
  • 60
  • 69
  • yes, but this unfortunately I can't do, look at my structure -- but maybe will not other way how to do... – user1946705 Jun 06 '11 at 19:56
  • Your structure's not very clear then... your first two "commands" match this answer. Why not paste your actual code? – Dylan Markow Jun 06 '11 at 20:00
  • Here is my currently controller: http://pastebin.com/UVV8XBXa and way, how I am trying to solve this situation – user1946705 Jun 06 '11 at 20:06
  • I am struggling with one problem yet... I got the ID of last inserted item, but I don't know why -- I can't save the ID from first table to second to save... If I try: puts first_instance_id -- so I get a number, but this number is not to save to column with datatype "int(11) not null" -- I tried also "first_instance_id.to_i", ut unfortunately without success... Did not meet anyone with similar problem? – user1946705 Jun 06 '11 at 20:22
1

Could you just search your database by the updated_at field in your model?

To get the most recent record:

@model1 = Model1.order("updated_at DESC").limit(1)

or better yet, upon saving Model1 in the first place:

@model1 = model1.save

To assign:

@model2.model1_id = @model1.id

Note: if you actually want to save the ID of a specific record, finding the last isn't the best way to go.

This is because another record could be inserted by a different user, right after you inserted Model1 and right before you call Model2.

If you want the two to save together or not at all, you can look into transactions: http://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html

If you're happy with Model1 saving on its own before worrying about Model2, then simply assign the variables as I did above.

sscirrus
  • 50,379
  • 41
  • 125
  • 211
1

After saving a model, you can access it's id variable:

@user = User.new
puts @user.id
# => nil
@user.save
puts @user.id
# => 1
Dylan Markow
  • 117,383
  • 23
  • 273
  • 197