Forum: Ruby on Rails data insertion in multiple tables

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
B26a42e6bedec6d55f1e48722702e088?d=identicon&s=25 Sung Soo Kim (Guest)
on 2005-12-26 17:04
(Received via mailing list)
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?
D6d48c40f1aee60c7dbfba68770148b2?d=identicon&s=25 Anocha Yimsiriwattana (Guest)
on 2005-12-26 17:31
(Received via mailing list)
Sung Soo Kim 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
8fd9f26b8f23d49c8a89b63f1279e24f?d=identicon&s=25 Chris Nolan.ca (Guest)
on 2005-12-26 18:04
(Received via mailing list)
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/
B26a42e6bedec6d55f1e48722702e088?d=identicon&s=25 Sung Soo Kim (Guest)
on 2005-12-26 21:35
(Received via mailing list)
I'm happy to hear that there is a solution.
 Thanks a lot.
This topic is locked and can not be replied to.