How do I update a has_and_belongs_to_many collection RESTfully?
The key to resolving this is to correctly identify the resource you are modifying. In this case, the resource you are modifying is the relationship between the class and the student, which I will refer to as an Enrollment
.
It has become customary in Rails to use has_many :through
preferentially to has_and_belongs_to_many
. You may want to change your domain logic to fit the custom, but you can also buck the trend, if you are truly certain that no metadata needs to be stored about the relationship.
One of the key ideas for REST is that RESTful resources do not need to map to models. You should create an EnrollmentsController
and add a line to config/routes.rb:
map.resources :enrollments
Then you can create and delete your relationships like so:
class EnrollmentsController < ApplicationController
def create
@student = Student.find(params[:student_id])
@course = Course.find(params[:course_id])
@student.courses << @course
if @student.save
#do happy path stuff
else
#show errors
end
end
def destroy
@student = Student.find(params[:student_id])
@course = @student.courses.find(params[:course_id])
@student.courses.delete( @course )
end
end
And you can make buttons for those actions like so:
<%= button_to "Enroll", enrollments_path(:student_id => current_student.id, :course_id => @course.id ), :method => :post %>
<%= button_to "Withdraw", enrollment_path(1, :student_id => current_student.id, :course_id => @course.id ), :method => :delete %>
The 1
on the line above acts as a placeholder where the :enrollment_id
should go and is a tiny bit of syntactic vinegar to remind you that you are bucking the will of the Rails framework.