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

时间:2015-08-13 17:43:28

标签: ruby-on-rails controller logic redirecttoaction

如何重定向到没有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

我想重定向到保存时没有UserLesson的下一课。我不知道怎么做,因为它属于一个章节。请帮忙!你可以帮我写一下这个查询......

1 个答案:

答案 0 :(得分:0)

以下是您问题的答案:

在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

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

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