2012-12-12 34 views
3

我有如下關係:Rails的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_valueCourseSignup模型。

你可以在the guide to ActiveRecord associations找到更多詳細信息。

+0

謝謝,雖然我可以避免創建一個新的模型 – fxe

1

你想要一個has_many :though,而不是一個HABTM。

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