Search code examples
ruby-on-railscontrollerlogicredirecttoaction

Ruby on Rails - redirect_to the next video that is not marked as completed


How can I redirect to the next lesson that does not have userLesson (problem is lessons belongs to a course through a chapter)

Models:

class Course
    has_many :lessons, through: :chapters
end

class Lesson
 belongs_to :chapter
 has_one :lecture, through: :chapter
end

class User
  has_many :user_lessons
end

class UserLesson
  #fields: user_id, lesson_id, completed(boolean)  
  belongs_to :user
  belongs_to :lesson
end

class Chapter 
  has_many :lessons
  belongs_to :lecture
end 

here user_lessons_controller:

class UserLessonsController < ApplicationController
  before_filter :set_user_and_lesson
  def create
    @user_lesson = UserLession.create(user_id: @user.id, lession_id: @lesson.id, completed: true)
    if @user_lesson.save
      # redirect_to appropriate location
    else
      # take the appropriate action
    end
  end
 end

I want to redirect_to the next lesson that has not the UserLesson when saved. I have no idea how to do it as it belongs_to a chapter. Please help! Could you please help me with the query to write...


Solution

  • Here is the answer for your question:

    Inside your user_lessons_controller:

    def create
      @user_lesson = UserLession.create(user_id: @user.id, lession_id: @lesson.id, completed: true)
      if @user_lesson.save
        #You have to determine the next_lesson object you want to redirect to
        #ex : next_lessons = current_user.user_lessons.where(completed: false)
        #This will return an array of active record UserLesson objects.
        #depending on which next_lesson you want, you can add more conditions in `where`.
        #Say you want the first element of next_lessons array. Do
        #@next_lesson = next_lessons.first
        #after this, do:
        #redirect_to @next_lesson 
    
      else
        #redirect to index?? if so, add an index method in the same controller
      end
    end
    

    This code will only work if you define show method in your UserLessonsController and add a show.html in your views.

    Also, in config/routes.rb, add this line : resources :user_lessons.