Rails 4 how to make enrolment to a course for users (controller, view, model)

431 Views Asked by At

I am currently trying to build a simple learning app with rails and I am facing problems. When a user signs up to a course i try to make a viewed_course record for them so that I can display all the viewed_course on their profile page.

I can't figure out how to set my different controllers so that it creates the viewed_record when I am on the Course Controller /index.

How can I modify the course/index view so that it creates a new viewed record for the current signed in user.

I am using devise.

class Course
    has_many :lessons
end

class Lesson
  #fields: course_id
  belongs_to :course
end
class User
  has_many :viewed_lessons
  has_many :viewed_courses
end
class ViewedLesson
  #fields: user_id, lesson_id, completed(boolean)  
  belongs_to :user
  belongs_to :lesson
end
class ViewedCourse
  #fields: user_id, course_id, completed(boolean)  
  belongs_to :user
  belongs_to :course  
end

Thank you so much in advance for helping me out!

1

There are 1 best solutions below

6
On BEST ANSWER

Something like this should do it, this is in courses controller show action (index action should be the list of all courses, show action should be viewing an individual course):

class CoursesController < ApplicationController
  def index
    @courses = Course.all
  end

  def show
    @course = Course.find(params[:id])
    current_user.viewed_courses.create(course: @course)
  end  
end

One gotcha is that this would create a new viewed course every time they viewed the page, you would need some logic to only add each course once.

Perhaps something like this:

def show
  @course = Course.find(params[:id])
  current_user.viewed_courses.create(course: @course) unless ViewedCourse.exists?(user_id: current_user.id, course_id: @course.id)
end