redirect_to更新时的下一个实例

时间:2016-06-19 05:47:33

标签: ruby-on-rails ruby-on-rails-4 redirect

我尝试在更新后将用户重定向到我的WordExposition模型的下一个实例。我目前使用的是立即相邻的word_exposition id,但如果下一课的word_exposition ID跳过(即它将在​​id' s之间正确重定向),则会引发RecordNotFound 1-4,但如果下一个id是6)将会中断。如何才能让它重定向到属于同一课程的那些不相邻的WordExposition实例?

我将next_exposition模型方法基于this帖子中的想法,但我遗漏了一些东西让它在这里工作。

WordExposition模型:

class WordExposition < ActiveRecord::Base
  belongs_to :enrollment
  belongs_to :word

  def next_exposition
    WordExposition.where(["id > ? AND enrollment_id = ?", id, enrollment_id]).first
  end
end

WordExpositions控制器:

class WordExpositionsController < ApplicationController
  def update
    current_word_exposition
    @current_word_exposition.completed = true
    @current_word_exposition.term_given_by_student = params[:word_exposition][:term_given_by_student]
    if @current_word_exposition.save
      flash[:notice] = "Congratulations!"
      #currently only redirects correctly for adjacent words in the same lesson, should do so for non-adjacent word_expositions in the same lesson
      if next_word = @current_word_exposition.next_exposition
        redirect_to lesson_word_exposition_path(current_lesson, next_word)
      end 
    else
      flash[:alert] = "Enter the word exactly as shown!"
      redirect_to lesson_word_exposition_path(current_lesson, current_word_exposition)
    end
  end

  private

  helper_method :current_lesson
  def current_lesson
    @current_lesson ||= Lesson.find(params[:lesson_id])
  end

  helper_method :current_enrollment
  def current_enrollment
    @current_enrollment ||= Enrollment.find_by!(lesson_id: params[:lesson_id], user_id: current_user.id)
  end

  def word_exposition_params
    params.require(:word_exposition).permit(:completed)
  end

  helper_method :current_word_exposition
  def current_word_exposition
    @current_word_exposition ||= current_enrollment.word_expositions.find_by!(word_id: params[:id])
  end
end

1 个答案:

答案 0 :(得分:0)

你可以试试这个

  def next_exposition
    WordExposition.where('id = (select min(id) from word_expositions where id > ?)', self.id).first
  end