3

I have to following relationship:

class Course < ActiveRecord::Base
  attr_accessible :name
  has_and_belongs_to_many :users
end

class User < ActiveRecord::Base
  attr_accessible :name
  has_and_belongs_to_many :courses
end

Then I have the following table:

create_table :courses_users, :force => true, :id => false do |t|
  t.integer :user_id
  t.integer :course_id
  t.integer :middle_value
end

How can I access (edit/update) the middle value in the many to many record?

James Chevalier
  • 10,604
  • 5
  • 48
  • 74
fxe
  • 575
  • 1
  • 4
  • 15

2 Answers2

4

HABTM should be used to only store the relation. If you have any fields you want to store in the relation, you should create another model, eg. CourseSignup. You would then use this model to create a has_many :through => :course_signups relation, so your models would look like this:

class Course < ActiveRecord::Base
  has_many :course_signups
  has_many :users, :through => :course_signups
end

class CourseSingup < ActiveRecord::Base
  belongs_to :course
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :course_signups
  has_many :courses, :through => :course_signups
end

Then you can add your middle_value in the CourseSignup model.

You can find more details in the guide to ActiveRecord associations.

Matt
  • 5,328
  • 2
  • 30
  • 43
1

You want a has_many :though, not a HABTM.

A HABTM does not have a join model, but a has_many :through does. Something like:

class Course < ActiveRecord::Base
  has_many :enrollments
  has_many :users, :through => :enrollments
end

class Enrollment < ActiveRecord::Base
  belongs_to :course
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :enrollments
  has_many :courses, :through => :enrollments
end
Todd
  • 3,438
  • 1
  • 27
  • 36