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.
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.
Just save it, then use the id
Seriously, this is a very common idiom, and you’ll find that rails takes
care of it.
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.
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 [email protected]
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.
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
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.