我有Risk模型。我想为每个risk存储预定义的User。
我应该如何实现Risk,使它能够处理不同类型的答案(整数、布尔、字符串)?表格应该是什么样子?现在,我正在考虑Risk如下:
Risk
question(string)
answer_type(integer)
answer我希望能够在未来动态地添加更多的问题。
发布于 2013-11-28 13:21:45
我的想法是:
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发布于 2013-11-27 12:51:13
理想情况下,
question(string)
answer (text)在风险模型中,添加一个基于问题的正确格式返回答案的方法。
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结束
https://stackoverflow.com/questions/20242756
复制相似问题