Ruby Rails - redirect_to 下一个未标记为已完成的视频

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

如何重定向到没有 userLesson 的下一课(问题是课程通过章节属于课程)

型号:

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 

此处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

我想redirect_to下一节没有UserLesson的课保存时。我不知道该怎么做,因为它 belongs_to 一章。请帮忙!你能帮我查询写...

这是您问题的答案:

在你的 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

仅当您在 UserLessonsController 中定义 show 方法并在视图中添加 show.html 时,此代码才有效。

此外,在 config/routes.rb 中添加此行:resources :user_lessons.