# Inserting the parent Id to the child table

**URL:** <https://www.ruby-forum.com/t/inserting-the-parent-id-to-the-child-table/95755>\
**Category:** Rails\
**Created:** [January 19, 2006, 8:22pm UTC](https://www.ruby-forum.com/t/inserting-the-parent-id-to-the-child-table/95755 "2006-01-19T20:22:26Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![unknown](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/4bbf92/32.png) [@unknown](https://www.ruby-forum.com/u/unknown)\
**Post date:** [January 19, 2006, 8:22pm UTC](https://www.ruby-forum.com/t/inserting-the-parent-id-to-the-child-table/95755/1 "2006-01-19T20:22:26Z")

</div>

The other day, I was looking at the way to insert into the child record.  
I looked at the api’s at the following link.  
[http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethod](http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethod)  
s.html

I am not very clear still the way to do it.

I would like to give you the background once again.

I have say two tables.  
Table A : students  
Table B : addresses

Table B has student\_id as the foreign key to Table A

If I am displaying the list of students and wanted to get individual  
students addresses based on their id, is the only option is to get the

id from students controller method list into the session and use that  
session value to populate the student\_id in the addresses table?

## ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ List.rhtml (students)
 \<%= link\_to("Address" , :controller =\> "addresses", :action =\> "list", :id =\> student) %\>
## Addresses\_controller

def list  
@addresses = Address.find(:all, :conditions =\> [ “student\_id=  
(?)”, params[:id]], :limit =\> 5)  
@session[“student\_id”] = params[:id] End

def create  
@addresses = Address.new(params[:addresses])  
@addresses.student\_id=@session[“student\_id”]  
…  
end  
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

I was told that this is not the right way, instead think in terms of the  
models something like this:

class Student \< ActiveRecord::Base  
has\_many :addresses  
…  
end

class Address \< ActiveRecord::Base  
belongs\_to :student  
…  
end

@student = Student.find(params[:id])  
@addrs = @student.addresses  
@address = @addrs.build(params[:address]) # and so on…

I am not very clear even after reading the api. Could someone give me an  
example of how this is can be achieved using ruby.

Thanks  
Silvy Mathews
