How can I create a has_many: user via a table without any user input attributes?

I have two models (users and courses) and a JOIN table that allows me to register with a 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 JOIN table to be credited has other attributes like class, percentage complete, etc. However, none of the attributes require input from the user other than registration. Ideally, the Id should have a link new_course_enrollment(@course, {:user_id => current_user} )

that creates the registration in the background (no need for the user to enter anything) and redirects back to the course page, with the "enroll" link replaced with the "enrolled" status. Is there a way to do this in models without having to change the RESTful Enrollments # new controller action?

0


source to share


1 answer


There are several ways to do this.

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

The form must have a hidden field with cursor_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 registration model.

+1


source







All Articles