如何处理不同的答案类型

时间:2013-11-27 12:38:44

标签: mysql ruby-on-rails ruby

我有Risk型号。我想为每个risk存储预定义的User

  1. 你吸烟吗?是的|不(布尔)
  2. 多少支香烟? (整数)
  3. 你是糖尿病患者吗? [since](字符串)

    ...

  4. 我应该如何实现Risk使其具有不同类型的答案(整数,布尔值,字符串)?表格应该怎么样?现在,我正在考虑如下Risk

    Risk
      question(string)
      answer_type(integer)
      answer
    

    我希望将来能够动态添加更多问题。

2 个答案:

答案 0 :(得分:1)

我的想法是:

Risk
  user_id (integer)
  question_id (integer)
  question(string)
  answer_type(integer)
  answer (string)

然后,如果你想制作一些统计数据,你需要解析答案取决于answer_type。

answer_type -> 1 for text answer
answer_type -> 2 for integer answer
...

例如,如果要计算整数答案的平均值:

risks = Risks.where(question_id: 1)
    if risk.answer_type == 2
      total += answer.to_i
    end
    average = total / User.all.count

答案 1 :(得分:-1)

理想地,

question(string)
answer (text)

在Risk模型中,添加一个方法,以正确的格式(基于)回答问题。

require 'string_extensions'
Class Risk
 ...

  def correct_answer
    if self.question == 'Are you smoker?'
      self.answer.to_bool # Add the Gist-code in your libs and include this 
    elsif self.question == 'How many cigarettes?'
      self.answer.to_i
    else 
      self.answer
    end
  end