【问题标题】:eagerloading with has_one association使用 has_one 关联进行急切加载
【发布时间】: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


【解决方案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

【讨论】:

  • 其实我发现一堆问题,比如 Question.find(:all)
  • 检查我更新的答案,如果现在不检查你是否检查过 railscasts :)
  • 您好,我是 Rails 新手,您能说说将在模型中放置什么代码以及如何访问视图中的变量。
  • %table %tr %th No %th Question %th Answer - @review_questions.each_with_index do |question,index| %tr %td= 索引+1 %td= question.text %td= question.answer
  • 非常感谢 Pritesh ,但它执行了很多次。示例:如果我们有 10 个问题,它将执行 20 次。我说的对吗?
猜你喜欢
  • 2017-08-28
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多