Rails how to make this view work? Devise, Enrolment system with courses

63 views Asked by At

How can I modify the view to make it work? I would like to have a "enroll now button" that will create a viewed_lessons record for the current_user?

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



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

Thank you for helping me out.

1

There are 1 answers

1
Lanny Bose On BEST ANSWER

In the model, you can validate for uniqueness...

viewed_course.rb

class ViewedCourse
  ...
  validates :course, uniqueness: { scope: :user, message: "should happen once per user" }
  ...
end

It doesn't look like you're using ViewedCourses in your show template. If you do later, you might want to try the find_or_create_by method in some instances.

One final piece of unsolicited feedback, your verbiage seems a little confusing to me. "Enroll" and "Show" feel like two very different actions.