我有以下型号。连接表引用user_id和course_id,组合设置为唯一。但是,在服务器上测试我的页面之后,例如多次离开和加入课程,还有另一个current_user我的连接表创建了course_id为空的记录。这让我在获取数据后出错。所以现在我尝试添加:false => null
。这有用吗? thx你的时间
def self.up
create_table :course_enrollments do |t|
t.references :user, :null => false
t.references :course, :null => false
t.timestamps
end
add_index :course_enrollments, [:user_id, :course_id], :unique => true
end
答案 0 :(得分:1)
当您尝试使用空ID保存:null => false
时,添加CourseEnrollment
将导致异常。如果您编写控制器操作来处理异常,那就没问题。您可以(并且应该)在CourseEnrollment模型中添加validates_presence_of :user_id, :course_id
,以便具有空ID的实例无效,并且可以使用正常的<model>.save
方法进行处理。
然而,更大的问题是为什么你的应用程序首先会保存带有空ID的行?例如,您可能正在创建孤立行(通过删除关联的课程或用户)。通常,最好在:dependent => :destroy
关联上添加has_many
以防止此情况发生。