导轨3.1,如何使用外键来计算的答案是多少? [英] rails 3.1, how to calculate answers number using foreign key?

查看:373
本文介绍了导轨3.1,如何使用外键来计算的答案是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下表格:

class FinalExam < ActiveRecord::Base
  belongs_to :course
  has_many :pages, :as => :course_unit, :dependent => :destroy
end

class Page < ActiveRecord::Base
  belongs_to :course_unit, :polymorphic => true
  has_one :quiz
  has_one :slide
end

class Quiz < ActiveRecord::Base
  belongs_to :page
end

class Answers < ActiveRecord::Base
  belongs_to :quiz
end

所以,我们有Answer.Quiz.Page.FinalExam

So, we have Answer.Quiz.Page.FinalExam

由于FianlExam ID,什么是找到所有的答案算最快的方法是什么?如何得到它?

Given the FianlExam id, what is the fastest way to find all Answers count ? how to get it ?

我可以重新设计数据库有 belongs_to的:在答案final_exam

I can re-design the DB to have belongs_to :final_exam in Answers

class Answers < ActiveRecord::Base
  belongs_to :quiz
  belongs_to :final_exam
end

这样一来,我可以说 Answers.where(:final_exam_id =&GT; PARAMS [:ID])。计数

我一定要改变数据库的设计?或者它是一个查询的问题?

Do I have to change the DB design ? or its a matter of a query ?

我需要一个专家的意见吧。

I need an expert advice please.

推荐答案

首先我猜测验应改为:

class Quiz < ActiveRecord::Base
  belongs_to :page
  has_many :answers
end

如果这样你就可以将这些行添加到您的 FinalExam 型号:

If so you can add these lines to your FinalExam model:

has_many :quizzes, :through => :pages
has_many :answers, :through => :quizzes

让您可以再调用

Allowing you to then call

FinalExam.first.answer.count

(注意:如果你在一个版本的Rails&LT的; 3.1,你需要这个插件

的缺点这种方式的是,它变成与大量数据慢。在这种情况下,你会想设置一个计数器缓存,更新每一个答案是补时FinalExam。它会因为你有很多层次的关系更复杂一些;看到这个帖子的详细信息:

The drawback to this approach is that it becomes slow with a lot of data. In this case, you'd want to set up a counter cache in the FinalExam that updates every time an answer is added. It'd a little more complicated because of the many-layered relationships you have; see this post for more info:

<一个href="http://stackoverflow.com/questions/4700247/counter-cache-has-many-through-sql-optimisation-reduce-number-of-sql-queries">counter_cache has_many_through SQL优化,减少SQL查询的数量

这篇关于导轨3.1,如何使用外键来计算的答案是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆