【发布时间】:2012-01-08 21:40:11
【问题描述】:
我的 Rails 应用程序中的连接表是多对多关系。我在我的模型中使用 has_many :through 成语。为简单起见,让我们调用我的第一类 Student、我的第二类 Course 和连接表类 Enrollment(包含字段 student_id 和 course_id)。我想确保给定的学生最多与给定的课程关联一次(即 {student_id, course_id} 元组在注册表中应该是唯一的)。
所以我有一个迁移 a 来强制执行这种唯一性。
def change
add_index :enrollments, [:student_id, :course_id], :unique => true
end
另外我的模型类是这样定义的:
class Student < ActiveRecord::Base
has_many :enrollments
has_many :courses, :through => :enrollment
end
class Course < ActiveRecord::Base
has_many :enrollments
has_many :students, :through => :enrollment
end
class Enrollment < ActiveRecord::Base
belongs_to :student
belongs_to :course
validates :student, :presence => true
validates :course, :presence => true
validates :student_id, :uniqueness => {:scope => :course_id}
end
在 Rails 控制台中,我可以执行以下操作:
student = Student.first
course = Course.first
student.courses << course
#... succeeds
student.courses << course
#... appropriately fails and raises an ActiveRecord::RecordInvalid exception
在我的 RSpec 测试中,我做了完全相同的事情,以下代码也没有例外:
@student.courses << @course
expect { @student.courses << @course }.to raise_error(ActiveRecord::RecordInvalid)
所以我的测试失败并报告:
expected ActiveRecord::RecordInvalid but nothing was raised
这里发生了什么?我可能做错了什么?我该如何解决?
【问题讨论】:
标签: validation ruby-on-rails-3.1 many-to-many rspec2 unique