Get information from multiply tables

Hi,

These are my models:


class Advisor < ActiveRecord::Base
set_table_name “advisors”
set_primary_key “id”

has_many :advisee, :class_name=>“Student”, :foreign_key=>
“advisor_id”
has_many :second_advisee, :class_name=>“Student”, :foreign_key=>
“sub_advisor”

end


class Student < ActiveRecord::Base
set_table_name “students”
set_primary_key “id”

belongs_to :advisor, :class_name=>“Advisor”, :foreign_key =>
“advisor_id”
belongs_to :second_advisor, :class_name=>“Advisor”, :foreign_key =>
“sub_advisor”

has_and_belongs_to_many :courses, :class_name=>“Course”

end


class Course < ActiveRecord::Base
set_table_name “courses”
set_primary_key “id”

has_and_belongs_to_many :students, :class_name=>“Student”

end

In my script/console>

How can i find the first student?
How can i find the first student and all her/his courses?

How can i find the first advisor ?
How can i find the first advisor students?

Thanks…remco

ok, let’s clean that up a bit, before we start

if you keep to naming conventions (as you do mostly)
it’s not necessary to tell rails every foreign_key or table name

class Advisor < ActiveRecord::Base

has_many :advisee, :class_name=>“Student”,
:foreign_key=>“advisor_id”
has_many :second_advisee, :class_name=>“Student”,
:foreign_key=>“sub_advisor”

end

class Student < ActiveRecord::Base

belongs_to :advisor
belongs_to :second_advisor, :class_name=>“Advisor”, :foreign_key =>
“sub_advisor”

has_and_belongs_to_many :courses

end

class Course < ActiveRecord::Base

has_and_belongs_to_many :students, :class_name=>“Student”

end

How can i find the first student?
@student = Student.find(:first)

How can i find the first student and all her/his courses?
@student = Student.find(:first)
@student.courses

@student.courses will be an array of courses
alternate:
@courses = Student.find(:first).courses

to loop through them eg:
@student.courses.each do |course|
puts course.name
end

How can i find the first advisor ?
@advisor = Advisor.find(:first)

How can i find the first advisor students?
@advisor.advisee

find offers lots of more search options, so you could find the first
created student:
@student = Student.find(:first, :order => “created_at DESC”)

He Thorsten,

Thanks!

Do you have some good url’s about this info?

remco

Do you have some good url’s about this info?

sorry, not like a tutorial
everything i did here is described in the Rails docs: