After I save a record in table A I want to save the id of that record in table B Immediatly

Hi all

I have two tables A and B I have saved a record in table A and I want to save the id of that record in table B. How Can I do that. Well I can do by search of same params which I save in Table A but I feel it is not that good approach. If the app is has multiple users than that is not good way can any one help to do it better.

Thanks in Advance

Just save it, then use the id :wink:

Seriously, this is a very common idiom, and you'll find that rails takes care of it.

You may need to reload the object, as in

if @whatever.save   @whatever.reload   @another_thing.whatever_id = @whatever.id   @another_thing.save end

That would only be true in a create method, because the ID isn't known until after the thing is saved. But if your relationships are declared in the usual way (has_many, belongs_to, etc.) then this plumbing is taken care of for you in most cases.

Walter

Thanks for your quick responses. Does I get the same id if I use @whatever.reload.

if that model is accessed often and there are multiple users working on same model and I want table A id to be saved as new record in table B

Table A

id name email

878 Sam sam@mail.in.com

as I save 878 record in Table A I want that 878 id to be saved as new record in table B

Table B

id table_a_id 900 878

If in this scenario does reload helps me considering that there will me more hits to Table A by multiple users.

As I suggested a little while ago when you first asked this question, but did not reply to my response, you should consider doing this using an association between the tables. Something like table_b belongs_to table_a, table_a has_many table_bs. Then rails will do a lot of the hard work for you. Almost always in rails if you are manipulating id values then you are doing it wrong.

Colin

Thanks for the response Colin my last mail was deleted some how anyway thanks for your reply. So If I use association between the tables

Table A Table B

has_many B and belongs_to A

now I save a new record to A

@table_a = TableA.save

@table_b = ?

what should be my next line so that id of that saved record will save in Table B

And how should we approach this with out association if there is no rails only Ruby project

help me on this

Thanks for the response Colin my last mail was deleted some how anyway thanks for your reply. So If I use association between the tables

Table A Table B has_many B and belongs_to A

now I save a new record to A @table_a = TableA.save @table_b = ? what should be my next line so that id of that saved record will save in Table B

Really, you need to work through some good tutorials to get the basics of rails. Also read the Rails Guides, in particular the one on Associations.

And how should we approach this with out association if there is no rails only Ruby project

Don't know.

Colin