【发布时间】:2012-08-22 14:37:30
【问题描述】:
我有两个模型,即下面的问题和选择
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 个选项中是正确的,它存储在问题表的答案列中。即question.answer
问题:当我显示所有我想显示选择文本的问题时,这意味着正确答案(即)@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
【问题讨论】:
-
其实我不知道怎么用eager loading,你能解释一下吗?示例问题:文本,答案(它是选择 id 之一)
标签: activerecord ruby-on-rails-3.1 ruby-on-rails-3.2