我必须遵循以下关系:
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如何访问(编辑/更新)多对多记录中的中间值?
发布于 2012-12-12 23:45:16
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然后,您可以在CourseSignup模型中添加middle_value。
您可以在the guide to ActiveRecord associations中找到更多详细信息。
发布于 2012-12-12 23:40:13
你要的是has_many :though,而不是HABTM。
HABTM没有join模型,但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
endhttps://stackoverflow.com/questions/13843201
复制相似问题