LoginSignup
9
3

More than 1 year has passed since last update.

Railsを使ったクイズアプリで問題を1問ずつ表示する方法

Posted at

前提

quizがquestionとアソシエーションの関係である。

class Quiz < ApplicationRecord
  has_many :questions, dependent: :destroy
end
class Question < ApplicationRecord
  belongs_to :quiz
end

以下のように問題を1問ずつ回答したのちに結果を表示させるような実装をしたい方は、ぜひ参考にしてみてください。

Image from Gyazo

実装方法

nextメソッドを定義する

class Question < ApplicationRecord
  belongs_to :quiz

  def next(quiz)
    quiz.questions.where("id > ?", self.id).order("id ASC").first
  end
end
  • "id > ?", self.idの部分で現在表示されているレコードよりもidが大きいレコードを取得
  • order("id ASC").firstでidが一番若いレコードを取得

引数にnextメソッドを使う

if @question.next(@quiz).present?
  redirect_to quiz_challenger_question_path(@quiz.id, challenger.id, @question.next(@quiz))
  # 引数にnextメソッドを使うことで、次のレコードへのpathを実装できる
else
  redirect_to quiz_challenger_path(@quiz.id, challenger.id)
end
  • もし次のレコードがある時、次のレコードへ遷移する
  • 次のレコードがなければ、回答結果画面に遷移する
9
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
3