I have two tables like:
Table A:
id (autoincrement)
name
Table B
id
id_of_A
desc
I want to add a record to table A and based on the id of A, I want to
add a
record to table B.
I don’t think there is any SQL command that support this (at least in
MySQL
4.1, so I use LAST_INSERT_ID()).
(Is there any other way? or MySQL 5 support any special SQL command?)
But I need this functionality to start my project.
Does Active Record support this functionality? or any other way to walk
around?
Or do I have to choose other databases than MySQL?
Sung Soo K. wrote:
I want to add a record to table A and based on the id of A, I want to add
a record to table B.
I don’t think there is any SQL command that support this (at least in
MySQL 4.1, so I use LAST_INSERT_ID()).
(Is there any other way? or MySQL 5 support any special SQL command?)
But I need this functionality to start my project.
Does Active Record support this functionality? or any other way to walk
around?
Or do I have to choose other databases than MySQL?
Hmm … let try this. I assume A and B has one to many relation, So A
can
have many B. The definition of A above is ok, but B has to change a bit,
say,
Table B
id
a_id
desc
That rails naming convention.
Now, in model for A, add
has_many :bs # that pural of b
and in model for B, add
belongs_to :a
Then in say A controller, method create, do this
def create
…
new_a = A.new params[:a] #well … depend on your view,
new_a.save
# at this point new_a has an id
new_b = B.new params[:b]
new_b.a = a # assing the a_id,
new_b.save
…
end
That should work.
tom
If you setup your relationships correctly AR will handle it
automatically for you.
e.g. a.b.create(“new description”)
is all you need and the a_id in the B table will be set automatically
and saved with your new item.
Chris Nolan.ca
http://kekova.ca/
I’m happy to hear that there is a solution.
Thanks a lot.