I have a has_and_belongs_to_many relationship, let’s say
class Student < ActiveRecord::Base
has_and_belongs_to_many :courses
end
class Course < ActiveRecord::Base
has_and_belongs_to_many :students
end
Now I have a form for a student, with a checkbox for applicable courses.
How do I validate the courses checked against some conditions, so that
if validation fails, the new associations are not saved?
I try, for example, in the student controller’s update method
@student.attributes = params[:student]
gather the course assignment from other parameters…
updated_courses = …
@student.courses = updated_courses.collect { |u| @student.courses.build
( u.attributes ) }
@successful = @student.save
But the courses for the student are then actually wiped out.
What is an easy way?
Thanks a lot,
Stephan