计算轨道中的调查响应

时间:2016-01-22 17:01:26

标签: ruby-on-rails activerecord

我是rails的新手,我想计算每个问题的不同选项的响应总数。如何计算每个问题的平均值。这些是我的模特。谢谢你的帮助。

class User < ActiveRecord::Base   
  has_many :surveys 
end

class Survey < ActiveRecord::Base
  belongs_to :user
  has_many :questions, :dependent => :destroy 
end

class Question < ActiveRecord::Base
  belongs_to :survey
  has_many   :options, :dependent => :destroy         
  has_many   :answers, :dependent => :destroy
end

class Option < ActiveRecord::Base
  belongs_to :question  
  has_many :answers, :dependent => :destroy
end

class Answer < ActiveRecord::Base
  belongs_to :option   belongs_to :question
end

1 个答案:

答案 0 :(得分:0)

您只需在问题类中创建一个字段,例如responseCount:integer,并在问题控制器中使用update来操纵您的数据。

def update
  # update 'response' count
end

一旦完成,您可以通过这样做来计算平均值:

@totalResponseCount = 0
@averageResponseCount = 0

for @question.each do  |question|
  totalResponseCount += question.responseCount
  averageResponseCount = totalResponseCount/Question.count
end