I got the following models. The join table references the user_id and the course_id and the combination is set unique. However, after testing my page on the server, e.g. leaving and joining courses many times,also with another current_user my join table created records where the course_id was empty. This got me errors in fetching data afterwards. So now I tried adding :false => null. Could this help? thx for your time
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
Adding
:null => falsewill cause an exception when you try to save aCourseEnrollmentwith a null ID. That’s fine if you write the controller action to handle the exception. You could (and should) addvalidates_presence_of :user_id, :course_idin the CourseEnrollment model, so that instances with null IDs will not be valid, and can be handled with the normal<model>.savemethod.However the bigger question is why does your app save rows with null IDs in the first place? For example, you might be creating orphaned rows (by deleting the associated Course or User). Generally it’s a good idea to add
:dependent => :destroyonhas_manyassociations to prevent this.