2012-12-12 2 views
3

값 : 다음레일 HABTM 중간 나는 다음과 같은 관계가

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 

나는이 다음 표 :

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

나는 (편집/업데이트) 많은의 중간 값에 액세스 할 수있는 방법 많은 기록?

답변

4

HABTM은 관계 만 저장하기 위해 사용해야합니다. 릴레이션에 저장할 필드가 있다면 다른 모델을 생성해야합니다. CourseSignup. 그런 다음 has_many :through => :course_signups 관계를 만들기 위해이 모델을 사용하므로 모델은 다음과 같을 것이다 :

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 

그런 다음 당신은 당신의 middle_value에서 CourseSignup 모델을 추가 할 수 있습니다.

자세한 내용은 the guide to ActiveRecord associations에서 확인할 수 있습니다.

+0

새 모델을 만드는 것을 피할 수는 있지만 고맙습니다. – fxe

1

HABTM이 아닌 has_many :though을 원하게됩니다.

HABTM에는 조인 모델이 없지만 has_many :through은 있습니다. 예 :

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