Inserting the parent Id to the child table


#1

Hi All,
I need your suggestions for the following. I am still learning RoR and
pardon my ignorance.
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
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Are there any other way to do this. Any help appreciated.
Thanks in advance.

Silvy Mathews


#2

It looks like you haven’t yet gotten the Rails way of doing this stuff.
Don’t think so much about the db, but think more about the models.

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…

Check out the docs on ActiveRecord associations, specifically has_many.

unknown wrote:

Hi All,
I need your suggestions for the following. I am still learning RoR and
pardon my ignorance.
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
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Are there any other way to do this. Any help appreciated.
Thanks in advance.

Silvy Mathews