我有一个 Course 模型,它有许多通过与连接表 CourseUser 的用户模型的关联。连接表有一个属性 type_str,它指定用户扮演的角色。我添加了验证以确保每个课程(用户对)的连接表中只存在一条记录。问题是如果该记录已经存在,则确保更新该记录,而不是添加一个新记录,这当然会使验证失败。
用户等级:
class User < ActiveRecord::Base
...
has_many :courses_enrolled_on, :through => :course_enrollees, :source => :course, :conditions => { :course_users => { :type_str => "enrollee" } }
has_many :course_users
has_many :courses, :through => :course_users, :source => :course, :readonly => true
end
课程班
class Course < ActiveRecord::Base
has_many :course_enrollees, :conditions => { :type_str => "enrollee" }, :class_name => CourseUser
has_many :enrollees, :through => :course_enrollees, :source => :user
has_many :course_users
has_many :users, :through => :course_users, :source => :user, :readonly => true
end
课程类别:
class CourseUser < ActiveRecord::Base
belongs_to :course
belongs_to :user
validates_uniqueness_of :course_id, :scope => :user_id
end