Ruby on rails rails 3.1,如何使用外键计算答案数?
我有以下表格:Ruby on rails rails 3.1,如何使用外键计算答案数?,ruby-on-rails,database,ruby-on-rails-3,activerecord,Ruby On Rails,Database,Ruby On Rails 3,Activerecord,我有以下表格: 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
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
这样,我可以说答案。其中(:期末考试\u id=>params[:id])。count
我必须改变数据库设计吗?还是一个疑问
我需要专家的建议。首先,我猜
测验应该是:
class Quiz < ActiveRecord::Base
belongs_to :page
has_many :answers
end
允许你打电话
FinalExam.first.answer.count
(注意:如果您使用的是Rails<3.1的版本,则需要)
这种方法的缺点是使用大量数据时速度变慢。在这种情况下,您需要在FinalExam中设置计数器缓存,该缓存在每次添加答案时都会更新。因为你有很多层次的关系,这会有点复杂;有关更多信息,请参阅本文:
在答案中添加“属于:期末考试”怎么样?然后使用:Answers.where(:final_-exam_-id=>params[:id])。count,您建议它远离复杂性吗?您还必须添加FinalExam有许多:答案。我不建议这样做,因为这样你就有了模棱两可的关系:期末考试的答案与期末考试的测验答案是分开的。你必须让这两组答案保持同步,这将是一场噩梦。有很多:通过是做你想做的事情的首选方式。
has_many :quizzes, :through => :pages
has_many :answers, :through => :quizzes
FinalExam.first.answer.count