0

我有两个模型,即问题和选择,如下所示

class Question < ActiveRecord::Base

  has_many :choices, :dependent => :destroy
  accepts_nested_attributes_for :choices, :allow_destroy => true
end

class Choice < ActiveRecord::Base
  attr_accessible :text
  belongs_to :question
end

这里每个问题有 3 个或更多选项,在这 3 个选项中是正确的,它存储在问题表的答案列中。即问题。答案

问题:当我显示所有我想显示选择文本的问题时,这意味着@choice Choice.find(@question.answer)它会显示正确的答案(即),@choice.text但它会导致n+1问题。

我们可以通过一个查询或像...这样的急切加载来实现这一点吗?

看法:

 %table
      %tr
        %th No
        %th Question  
        %th Answer
      - @review_questions.each_with_index do |question,index|
        %tr
          %td= index+1
          %td= question.text
          %td= question.answer
4

1 回答 1

1

急切加载是一次收集所有需要的数据,在某些n+1情况下使用完整

这些将运行两个查询

  1. 查找所有问题

  2. 一个查询中所有问题的所有问题选择并缓存它

您可以通过以下方式访问每个问题的选项

@question.each do |question|
 choices = question.choices
 correct_choice = choices.detect{|choice| choice.id = question.answer}  
end

并通过以下方式找到答案的选择

// return the choice with id @question.answer

有关急切加载的更多详细信息

http://railscasts.com/episodes/22-eager-loading

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

示例如何使用

控制器:

@questions = Question.all(:include=>:choices)

问题模型:

def correct_answer
   choices.detect{|choice| choice.id = self.answer}  
end

观点:(对不起,我不太擅长haml,从来没有尝试过,如果有任何问题,请纠正)

%table
  %tr
    %th No
    %th Question  
    %th Answer
  - @questions.each_with_index do |question,index|
    %tr
      %td= index+1
      %td= question.text
      %td= question.correct_answer.text
于 2012-08-23T09:26:58.027 回答