循环a记录集合时如何查询另一个表?

时间:2017-10-21 09:46:55

标签: ruby-on-rails activerecord

我想循环一组记录,并从另一个表中检查答案状态。 查看部分中描述的详细信息。

模型

# 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

DB

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>

我想知道是否有办法清楚地做到这一点?

1 个答案:

答案 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>