我試圖讓在Rails網上問答系統5.Rails的多對多IDS
這裏有一些機型:
quiz
,question
,quiz_question
,answer
,category
questions (:title, :category_id, type_id)
answers (:title, :is_right)
個quizzes (:title, :category_id, question_count, question_ids)
的關聯是:
class Quiz < ApplicationRecord
has_many :questions, :through => :quiz_questions
belongs_to :category
end
class QuizQuestion < ApplicationRecord
belongs_to :quiz
belongs_to :question
end
class Question < ApplicationRecord
has_many :answers, inverse_of: :question, :dependent => :destroy
accepts_nested_attributes_for :answers, allow_destroy: true, reject_if: :all_blank
belongs_to :category
belongs_to :type
has_many :quizzes, :through => :quiz_questions
end
產生一個新的測驗時,我們得到的是提問的類別,問題的集合。
的問題的數量也許所有的類別,或只是其中的一部分,如100或200
這裏是我的問題:
如果有必要創建
QuizQuestion
模式建立many-to-many
關聯?我想使用
question_ids
,quizzes
這一列來存儲測驗從問題表中按類別得到的問題。 但是有太多的問題,無法選擇所需的問題。如何實現這一點?
謝謝您的回覆。有很多有價值的觀點。正如你所說,我仍然使用'has_many:through'。我遇到了另一個問題:當使用'quiz.questions'時,有許多SQL查詢像'SELECT COUNT(*)FROM「questions」INNER JOIN「quiz_questions」ON ...'。計數' – floox
你在循環內使用它嗎?因爲每次調用'quiz.questions.count'時,rails應該只會生成一個查詢... – drosboro