我想循环一组记录,并从另一个表中检查答案状态。 查看部分中描述的详细信息。
# Quiz
class Quiz < ApplicationRecord
has_many :quiz_questions
has_many :questions, :through => :quiz_questions
has_many :quiz_details
end
# QuizDetail
class QuizDetail < ApplicationRecord
belongs_to :quiz
end
# QuizQuestion
class QuizQuestion < ApplicationRecord
belongs_to :quiz
belongs_to :question
end
# quiz_questions_controller.rb
def index
@questions = @quiz.questions
# @quiz_details = @quiz.quiz_details
end
create_table "quiz_details", force: :cascade do |t|
t.integer "quiz_id"
t.integer "question_id"
t.integer "user_id"
t.boolean "is_correct", default: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
<ul>
<% @questions.each do |question| %>
<li>
# I want to check the answers status
# The status in the quiz_details table
# `is_correct` : true or false
<%= link_to question.title, quiz_question_path(@quiz, question) %>
</li>
<% end %>
</ul>
我想知道是否有办法清楚地做到这一点?
答案 0 :(得分:0)
我认为您需要添加更多关联才能使其顺利运行。如果我正确读取数据库表,quiz_details
也属于questions
。您可以按如下方式添加该关联:
添加到模型
# Question
class Question < ApplicationRecord
has_many :quiz_details do
def by_quiz(quiz)
where(quiz_id: quiz.id)
end
end
end
# QuizDetail
class QuizDetail < ApplicationRecord
belongs_to :quiz
belongs_to :question
end
在控制器
中 def index
# If you iterate over questions use this:
@questions = @quiz.questions.includes(:quiz_details)
# If you iterate over quiz_details use this:
@quiz_details = @quiz.quiz_details.includes(:question)
end
在查看
中如果你肯定需要迭代questions
:
<ul>
<% @questions.each do |question| %>
<li>
<%= question.quiz_details(@quiz).first.is_correct %>
<%= link_to question.title, quiz_question_path(@quiz, question) %>
</li>
<% end %>
</ul>
然而,这可能会产生令人讨厌的N + 1查询效率低下。您可以检查控制台以查看是否存在。
更好的方法是尽可能迭代quiz_details
:
<ul>
<% @quiz_details.each do |detail| %>
<li>
<%= detail.is_correct %>
<%= link_to detail.question.title, quiz_question_path(@quiz, detail.question) %>
</li>
<% end %>
</ul>