many-to-many Association with HABTM

hey guys,

Basically i've already setup a many-to-many relationship between the 2 models and setup a Intermediate join Table without a primary_key on the join table.

so i've done this

class Student < ActiveRecord::Base        has_and_belongs_to_many :teachers end

and

class Teachers < ActiveRecord::Base        has_and_belongs_to_many :students end

i've also created the following table

students_teachers

with the columns teacher_id and student_id

however when I try to create a student (logged in as the teacher trying to create student record)

Where in the Student#Create Controller i am doing

@teacher = Teacher.where(['id=?', session[:logged_teacher].techerId]).first @student = @teacher.students.build(params[:student])

however when I try to create the user and save in the database the record is being created in the student table however the Join Table is not being populated. Am I doing something wrong here? am I missing out on something?

Thx

use have many through is better and easier

Do you save the @teacher after you've built the @student? Your code all looks okay at first glance and seems to match what the docs say:

But there is possible typo in there:    @teacher = Teacher.where(['id=?', session[:logged_teacher].techerId]).first

...should that be "teacher_id" rather than "techerId"? and you could just do @teacher = Teacher.find(session[:logged_teacher].techerId)

As and aside, I'd recommend *not* saving whole Teacher objects in the session - rather, just save their ID and retrieve them again from the DB on the next request. I've seen problems in applications where one too many objects gets saved in the session for the available space, and much confusion ensues! :slight_smile: