2014-11-25 6 views
1

У меня есть база данных, в которой хранятся ответы учащихся на вопросы викторины. Они связаны с результатами обучения учащихся, которые я хочу рассмотреть в рамках ряда взаимосвязей, описанных ниже. Я пытаюсь подсчитать, сколько ответов было правильно ответировано и сколько ответов было задано неправильно для каждого результата обучения ученика, но я продолжаю получать ошибки. Заранее благодарю за любую помощь, которую вы предоставляете.Rails вложенные соединения с has_many через отношения

Общее отображение

«Ответ» отвечает на вопрос, который проверяет на «KnowledgeTopic», который охватывает многие («KtCoveredBySLO») «StudentLearningOutcome»

Мои модели имеют следующие соотношения:

class Answer < ActiveRecord::Base 
    belongs_to :KnowledgeTopic 
end 

class KnowledgeTopic < ActiveRecord::Base 
    has_many :answers 
    has_many :kt_covered_by_slos 
    has_many :student_learning_outcomes, through: :kt_covered_by_slos 
end 

class KtCoveredBySlo < ActiveRecord::Base 
    belongs_to :StudentLearningOutcome 
    belongs_to :KnowledgeTopic 
end 

class StudentLearningOutcome < ActiveRecord::Base 
    has_many :kt_covered_by_slos 
    has_many :knowledge_topics, through: :kt_covered_by_slos 
end 

запрос Я пытаюсь запустить это:

@answers = Answer.joins(:KnowledgeTopic => {:kt_covered_by_slos => :StudentLearningOutcome}) 

.select('student_learning_outcomes.id As student_learning_outcomes_id', 
       :is_correct, "count(answers.id) AS total_answers") 

.group('student_learning_outcomes.id', :is_correct) 

Ошибка я получаю это:

SQLite3 :: SQLException: нет такой колонки: kt_covered_by_slos.knowledge_topic_id:. ВЫБРАТЬ student_learning_outcomes.id Как student_learning_outcomes_id, "ответов" "is_correct", граф (answer.id) AS total_answers FROM "отвечает" INNER JOIN "knowledge_topics" ON "knowledge_topics". "id" = "ответы". "KnowledgeTopic_id" INNER JOIN "kt_covered_by_slos" ВКЛ "kt_covered_by_slos". "knowledge_topic_id" = "knowledge_topics" . "id"
INNER JOIN "student_learning_outcomes" ВКЛ.."student_learning_outcomes" "ID" = "kt_covered_by_slos" "StudentLearningOutcome_id" GROUP BY student_learning_outcomes.id, is_correct

Миграции:

class CreateKtCoveredBySlos < ActiveRecord::Migration 
    def change 
    create_table :kt_covered_by_slos do |t| 
     t.references :StudentLearningOutcome, index: true 
     t.references :KnowledgeTopic, index: true 

     t.timestamps 
    end 
    end 
end 

class CreateAnswers < ActiveRecord::Migration 
    def change 
    create_table :answers do |t| 
     t.references :Question, index: true 
     t.references :Section, index: true 
     t.references :Student, index: true 
     t.references :KnowledgeTopic, index: true 
     t.boolean :is_correct 
     t.string :answer_text 
     t.references :Enroll, index: true 

     t.timestamps 
    end 
    end 
end 

class CreateKnowledgeTopics < ActiveRecord::Migration 
    def change 
    create_table :knowledge_topics do |t| 
     t.string :knowledge_area 
     t.string :knowledge_unit 
     t.string :knowledge_topic 
     t.integer :year_added 
     t.boolean :active 
     t.integer :correct_answers 
     t.integer :incorrect_answers 
     t.integer :temp_correct_answer 
     t.integer :temp_incorrect_answer 
     t.timestamps 
    end 
    end 
end 

class CreateStudentLearningOutcomes < ActiveRecord::Migration 
    def change 
    create_table :student_learning_outcomes do |t| 
     t.string :accredidation_body 
     t.string :title 
     t.string :description 
     t.integer :year_added 
     t.boolean :active 
     t.integer :correct_answers 
     t.integer :incorrect_answers 
     t.integer :temp_correct_answer 
     t.integer :temp_incorrect_answer 
     t.timestamps 
    end 
    end 
end 
+0

Можете ли вы обновить свой вопрос миграциями для 'Ответ',' KtCoveredBySlo'? В запросе отображаются два разных имени столбца для внешнего ключа «KnowledgeTopic». – vee

+0

Можете ли вы также структурировать свои запросы так, как их легче читать, например, разделять их на несколько строк. –

+0

Вы пытались выполнить соглашение по rails и использовать имена snake_case в ваших объявлениях миграции и ассоциации в моделях или это не вариант? – ave

ответ

1

Спасибо Всем. Используя объяснение Аве, я изменил имена ссылок, а затем обновил все остальное. После этого я смог выполнить запрос с

@answers = Answer.joins(knowledge_topic: :student_learning_outcomes) 
.select('student_learning_outcomes.id As student_learning_outcomes_id', :is_correct, 
    "count(answers.id) AS total_answers") 
.group('student_learning_outcomes.id', :is_correct)