views:

181

answers:

1

I have two models (users and courses) and a JOIN table that allows enrollments in the course:

class User < ActiveRecord::Base
 has_many :enrollments, :dependent => :destroy
 has_many :courses,     :through => :enrollments
end

class Course < ActiveRecord::Base
 has_many :enrollments, :dependent => :destroy
 has_many :users,       :through => :enrollments
end

class Enrollment < ActiveRecord::Base
  belongs_to :user
  belongs_to :course
end

The enrollments JOIN table has other attributes such as grade, percent completed, etc. However, none of the attributes require input from the user, other than enrolling. Ideally, I’d like to have a new_course_enrollment(@course, {:user_id => current_user} ) link that creates the enrollment in the background (no need for the user to input anything) and redirects back to the courses page, with the “enroll” link replaced by “enrolled” status. Is there a way to do this in the models, without needing to change the default RESTful Enrollments#new controller action?

+1  A: 

There are several ways to do this.

In the view you can create an inline form with the 'enroll now' anchor text, pointing to your 'new_course_enrollment' method.

The form should have a hidden field with the course_id.

Then in your controller, you need this code.

def new_course_enrollment
  e = Enrollement.new
  e.user_id = current_user
  e.course_id = params[:course_id]
  e.save

  redirect_to :action => 'index' # list of courses here
end

You can of course refactor this code to make it shorter, move it to a private method in the controller or, more logically, to the Enrollment model itself.

allesklar